Home > Back-end >  What is the best way to subtract the previous element from the current element in an array?
What is the best way to subtract the previous element from the current element in an array?

Time:10-21

My goal is to subtract the previous element from the current element in an array.

I.e.

Index position 1 - Index position 0 , then

index position 2 - index position 1 , then

index position 3 - index position 2

double[] arr = { 1, 22, 13, 4 };

So: 22 - 1 = 21, then 13 - 21 = -8, then 4 - (-8) = 12

The values in the array should look like this after the operation.

double[] arr = { 1, 21, -8, 12 };

My approach is as follows:

double[] array = new double[matrix[0].length - 1];

    DoubleBinaryOperator operator = (x, y) -> y - x;

        for (int i = 0; i < arr.length - 1; i  ) {
            Arrays.parallelPrefix(arr, i, i   1, operator);
        }
    

I thought I would use parallelPrefix to perform this operation.

The operator is (x, y) -> y - x..

The array is iterated over and the parallelPrefix method is executed exactly as many times as the length of the array. During execution, the bounds to be calculated are always specified.

But unfortunately the values are not changed.
Do you have an idea where the error could be?

CodePudding user response:

Don’t loop over your array. That is the job of the parallelPrefix method. Use Arrays.parallelPrefix(arr, operator); to apply your operator to the entire array.

Arrays.parallelPrefix(arr, i, i 1, operator); applies operator to a sub-array which consists of only the array element at index i. (The third method argument, i 1, is an exclusive bound, which means all array indices from i up to but not including i 1 are affected—which translates to only the element at i.)

The reason you are not seeing any results is that you are repeatedly applying your operator to a sub-array of length 1. Obviously it’s not possible to perform any subtractions with only one array element.

CodePudding user response:

As noted in the answer from @VGR, all you need to do is:

double[] arr = { 1, 22, 13, 4 };
java.util.function.DoubleBinaryOperator operator = (x, y) -> y - x;
java.util.Arrays.parallelPrefix(arr, operator);
System.out.println(java.util.Arrays.toString(arr));

Running the above code displays the following:

[1.0, 21.0, -8.0, 12.0]

As stated, by @JohnnyMop in his comment, the last array element is 12 and not -4.

  • Related