Computing sum of values in array - java

The problem im getting is that with oddSum the value outputted is the same as evenSum, and the value for sum of all elements is 0.
I cant quite see where im going wrong as the loops are pretty similar and if the even one works the others should too?
Here is my code anyway:
int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
}
else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
evenSum =evenData[evenIndex] + evenSum;
}
System.out.print("Sum of even elements: " + evenSum);
for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{
oddSum = oddData[oddIndex] + oddSum;
}
System.out.print("Sum of odd elements: " + oddSum);
for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);

You are getting same value for even and odd because you are printing the same value: -
System.out.print("Sum of odd elements: " + evenSum);
Also, your final sum is zero because you are making out all the elements of your original array as zero, as you are swapping your elements with the elements in evenData and oddData, which are zero initially.
int temp = data[index];
data[index] = evenData[index]; // This code assigns a value 0 to current index.
evenData[index] = temp;
So, you are iterating your array, and assigning 0 to each of your index, while adding the previous element to the new array.
I would say that you are needlessly using 2 extra array and 3 extra loops. Why not just create a sum in the place where you are iterating your original array?
In fact, all your sums can be computed in a single loop: -
for(int index = 0; index < data.length; index++)
{
sum += data[index];
if (data[index] % 2 == 0)
{
// int temp = data[index];
// data[index] = evenData[index];
// evenData[index] = temp;
evenSum += data[index];
}
else
{
// int temp = data[index];
// data[index] = oddData[index];
// oddData[index] = temp;
oddSum += data[index];
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
System.out.println("Total Sum: " + sum);
So, you don't need to create extra arrays for even and odd numbers.
And, also your 4 loops have now been condensed to just a single loop.

int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
Looking at your above lines, evenDate is empty and in second line you are setting your data array to be empty. You are repeating the same mistake in oddDate line as well.
Why don't you use just try the following?
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0) {
int temp = data[index];
evenData[index] = temp;
} else {
int temp = data[index];
oddData[index] = temp; }
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
//since length of all 3 data,even, odd arrays are the same
//you can put both sum operation in one for loop
evenSum = evenData[evenIndex] + evenSum;
oddSum = oddData[evenIndex] + oddSum;
sum = data[evenIndex] + sum;
}
System.out.print("Sum of even elements: " + evenSum);
//you have put evenSum for below odeUm printing in ur code
System.out.print("Sum of odd elements: " + oddSum);
System.out.print("Sum of all elements: " + sum);

Related

print the summation of an array

I need to create an array of 1 to 100 and print the summation of the elements.
Actually, I have used for loop and Array together! But it won't work.
int i, sum = 0;
for(i = 1; i < 100; i++) {
int [] arr = new int [] {i};
sum = sum + arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
}
A "one-liner" solution.
int[] arr = {...}; // Your array here
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i]; // can also be written as sum += arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
If the array is empty, the sum will be zero. Otherwise, it is the accumulated sum. The best thing to do is to declare and increment the loop counter variable inside the for structure and not outside. That's how it is designed. If you need this variable accessible outside the loop, use a while loop instead.
UPDATE: In case you're curious for a while loop equivalent:
int[] arr = {...}; // Your array here
int sum = 0;
int i = 0;
while (i < arr.length) {
sum = sum + arr[i]; // can also be written as sum += arr[i];
i++; // always increment the variable at the end of the loop
}
I think you are looking for something like this:
int i, sum = 0;
int[] arr = new int[100];
for(i = 0; i < arr.length; i++) {
arr[i] = i+1;
sum += arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

Subarray sum equal to k for negative and positive numbers in less than O(n2)

I can search for subarrays with sum eqaul to k for positive numbers but the below code fails for negative numbers in arrays. Is there an algorithm for finding subarrays with a given sum for negative and positive numbers in an array ?
public static void subarraySum(int[] arr, int sum) {
int start=0;
int currSum=arr[0];
for(int i = 1;i<=arr.length;i++) {
while(currSum>sum ) {
currSum-=arr[start];
start++;
}
if(currSum==sum) {
System.out.println(start + " " + (i-1) + " index");
start=i;
currSum=0;
}
if(i<arr.length) {
currSum +=arr[i];
}
}
}
For example, {10, 2, -2, -20, 10}, find subarray with sum -10 in this array.
Subarray in this case would be {-20, 10}.
O(N^2) solution
For each index i precalculate the sum of subarray from 0 to i, inclusively. Then to find sum of any subarray (i, j) you can just calculate sum[j] - sum[i] + arr[i].
public static void subArraySum(int[] arr, int target) {
if (arr.length == 0) return;
int n = arr.length;
int[] sum = new int[n];
sum[0] = arr[0];
for (int i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + arr[i];
}
for (int i = 0; i < n; ++i)
for (int j = i; j < n; ++j)
if (sum[j] - sum[i] + arr[i] == target) {
System.out.println(i + " " + j);
}
}
Faster solution
You can find subarray faster if you will store the sums in the map and then query this map for the required sum.
public static void subArraySum(int[] arr, int target) {
if (arr.length == 0) return;
int n = arr.length;
int[] sum = new int[n];
sum[0] = arr[0];
for (int i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + arr[i];
}
Map<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < n; ++i) {
if (sum[i] == target) {
System.out.println(0 + " " + i);
}
int requiredSum = sum[i] - target;
if (map.containsKey(requiredSum)) {
int startIndex = map.get(requiredSum) + 1;
System.out.println(startIndex + " " + i);
}
map.put(sum[i], i);
}
}
This solution is O(N*logN), but you can make it faster if you will use HashMap instead of TreeMap (O(N) if you assume that HashMap operations complexity is constant).
Note that this solution will not print all possible pairs. If you need to find all subarrays with given sum you need to have Map<Integer, Array<Integer>> instead of Map<Integer, Integer> and store all indexes with given sum.

calculating the sum between two integers (java)

What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}

could some explain me this permuation/derangement program

Hi can some one please explain me the below derangement/permutation program in a simple way.
From past one week I am banging my head to understand the program. I have understood all the methods but I am not able to understand the "else part". I have tried debugging the program but didn't get clarity to what is happening in the else part.
import java.util.Scanner;
public class Deranged {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int num = s.nextInt();
System.out.println("Number :" + num);
int size = digitSize(num);
System.out.println("Size :" + size);
System.out.println("Permutation :" + fact(size));
int swap = fact(size);
int array[] = digitArray(num, size);
if (size < 3) {
if (size < 2) {
System.out.print(num);
} else {
System.out.println(array[0] + "" + array[1]);
System.out.println(array[1] + "" + array[0]);
}
} else { // NEED CLARITY FROM HERE
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
}
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
}
}
}
public static int fact(int num) {
int factNo = 1;
for (int i =num; i > 0; i--)
{
factNo = factNo * i;
}
return factNo;
}
public static int digitSize(int num) {
//int count = String.valueOf(num).length();
// return count;
int count = 0;
while(num>0)
{
num/=10;
count++;
}
return count;
}
public static int[] digitArray(int num, int size) {
int count[] = new int[size];
int i = size - 1, rem;
while (num > 0) {
rem = num % 10;
count[i] = rem;
num = num / 10;
i--;
}
return count;
}
}
In the code size is the number of digits in your number and swap is the factorial of the number of digits. For example, if you enter a 5 digit number the fact function calculates 5 * 4 * 3 * 2 * 1. array is just a list of the digits you entered, ordered from the least significant digit to the most significant.
So here is the pseudo code for the case where the number of digits is 3 or greater. I've interleaved the code to make it clearer.
i = 2
For each digit in the array of digits indexed by outer
- Set fix to the digit currently stored in the first element of the array
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
For each index j from 1 to the factorial of the number of digits divided by number of digits
- If i is equal to the number of digits, set i equal to 2
- Swap digit i-1 with digit i in the digit array
- Increment I
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
Set uniqueNo to the decimal number that the digit array currently represents, except that fix is the least significant digit
Print the uniqueNo for the current value of j
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
If the current value of outer is the last element in the digit array
- Swap the first digit with the last digit in the array
Else
- Swap the first digit of the array with the digit at outer+1
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
The code is basically iterating factorial/number of digit times for each digit of the number that was input and rearranging the digits with each iteration in a way that wraps around from the last digit to the first. It's difficult to understand partly because the variable names are uninformative.
The number of permutations of n distinct objects is n! (factorial), so the code is just listing all possible permutations of the digits of the number that was input. If there are only 2 digits, there are only two permutations, and of course 1 digit has only one permutation, so those are special cases. If you iterate through each digit, the maximum number of permutations keeping one digit "fixed" is factorial/number of digits.

Categories

Resources