List<Double> list2 = new ArrayList<Double>();
double[]numbers= {13,17,14};
//Arrays.sort(numbers);
// start with last number
// double diff = numbers[numbers.length-1];
//double temp = 0;
list2.add((double)0);
for(int j =1;j<=numbers.length-1;j ) {
double temp = 0;
double temp2 = 0;
int cnt1 =0;
// System.out.println("cnt1 --> " cnt1);
for (int i=j; i>=0; i--) {
// substract other number one by one
if(i > numbers.length-1) {
break;
}
System.out.println("Answer i --> " i " - " numbers[i]);
// System.out.println("Answer cnt1 --> " cnt1 " - " numbers[cnt1]);
//temp = numbers[i] -numbers[cnt1];
temp = temp - numbers[i] ;
temp = Math.abs(temp);
System.out.println("temp --> " temp);
//cnt1 ;
//System.out.println("cnt1 --> " cnt1);
}
list2.add(temp);
//temp = 0;
}
// System.out.println("Answer --> " diff);
System.out.println("Answer --> " list2);
I am writing code to perform the substraction of array element. For given array element substraction array element should (0,4,-16) . First element is 0 because no element at left side of first element. Can you please suggest why I am getting (0,4,10) instead of (0,4,-16)
CodePudding user response:
During the last iteration, temp - numbers[i]
becomes 3 - 13
which results in -10
. When the absolute value is taken using Maths.abs(temp)
, the value becomes 10
. Hence, you obtain the result as [0,4,10]
.
Since you are sequentially trying to subtract the elements, during each subtraction, the result should be stored in a temp
variable and subtracted again from the previous temp
variable value.
For example, if we consider the second iteration which subtracts 14 - 17 - 13
,
- during the first subtraction ->
temp = 14 - 17 = -3
- during the second subtraction ->
temp = temp(-3) - 13 = -16
From this we can see that, before the first subtraction, if we put 14
in to the temp
variable, you will get the expected output.
- during the first subtraction ->
temp = temp(14) - 17 = -3
- during the second subtraction ->
temp = temp(-3) - 13 = -16
The first subtraction occurs within the second loop. So, within the first loop, we can assign the first value which should be considered for the subtraction to the temp
variable.
You could modify your loops as follows.
for(int j=1; j<=numbers.length-1; j ) {
double temp = numbers[j];
for (int i=j; i>0; i--) {
temp = temp - numbers[i-1];
}
list2.add(temp);
}