HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sum pairs of numbers in array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraynumberspairssum

Problem

This code takes a list of ints and sums their pairs, storing the summed pairs in an array sumPairs, then returning that array. If the supplied array toSum has an odd number of elements, it returns the sumPairs with the last element of the toSum as the last element of sumPairs. Any suggestions for improving my code, or accomplishing this task in a better way, would be most appreciated!

public static int[] collapse(int[] toSum) {
    int[] sumPairs = new int[toSum.length / 2 + toSum.length % 2]; 
    for (int i = 0, j = 0; i < toSum.length - 1; i+=2, j++) {
        sumPairs[j] = toSum[i] + toSum[i + 1];
    }
    if (toSum.length % 2 == 1 && sumPairs[sumPairs.length - 1] == 0) { 
        sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1]; 
    }
    return sumPairs;
}

Solution

Looks good! :)

The only thing I can spot is that the second condition for your if statement is unnecessary, as the first condition is all that is required. Therefore:

if (toSum.length % 2 == 1) {
    sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}

Code Snippets

if (toSum.length % 2 == 1) {
    sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}

Context

StackExchange Code Review Q#95920, answer score: 4

Revisions (0)

No revisions yet.