stronghold051
stronghold051

Reputation: 342

how to add values in an array from last value to first

How can I add the values in the arrNumbers that exceed 6 to add to a new array starting from the last value and ending at the first.

This is what I have written, but does not produce the right output.

    int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
    int[] newArrNumbers = new int[6];

    for(int i  = 0; i < arrNumbers.length ; i++){
        newArrNumbers[i % 6] += arrNumbers[i];
    }

The actual output:

newArrNumbers = [2, 4, 3, 4, 5, 6]

However, I want the output to ADD to the LAST VALUE in the arrNumbers, going from right to left, not left to right. So result should be:

newArrNumbers = [1, 2, 3, 4, 7, 7]

Upvotes: 0

Views: 68

Answers (1)

user4910279
user4910279

Reputation:

Try this.

int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
int[] newArrNumbers = new int[6];

for(int i  = 0; i < arrNumbers.length ; i++){
    newArrNumbers[i < 6 ? i : (6 - (i % 6) - 1)] += arrNumbers[i];
}
System.out.println(Arrays.toString(newArrNumbers));

output:

[1, 2, 3, 4, 7, 7]

Upvotes: 1

Related Questions