Uma
Uma

Reputation: 33

Summing up the outer elements in a 2D array of integers in Java?

One of the questions from my exam asked to write some code to compute the sum of the outer int elements of a 2D array. Length of rows and length of columns aren't necessarily equal.

[EDIT] Corner values cannot be added more than once.

I came up with this code and it works, but I'd like to know if there are more efficient ways to achieve the same results. Thanks.

for(int i = 0; i < in.length; i ++) { for(int j = 0; j < in[i].length; j++) { if(i == 0 || i == in.length - 1) { sum += in[i][j]; } else { sum += in[i][in[i].length - 1 ] + in[i][0]; break; } } }

Upvotes: 2

Views: 2669

Answers (2)

Denis
Denis

Reputation: 1229

Yes you can do it more efficiently.

int row = in.length;
int column = in[0].length;//not sure of this syntax but trying to get the column size
int sum = 0;

for(int j=0;j<column;j++)
{
    sum+=in[0][j]+in[row-1][j];
}
for(int j=1;j<row-1;j++)
{
    sum+=in[j][0]+in[j][column-1];
}

Your solution is O(mn) and the loop iterates through unnecessary indexes.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

If I understand your question, then you could first extract a method to add the elements of one array like

public static int sumArray(int[] in) {
    int sum = 0;
    for (int val : in) {
        sum += val;
    }
    return sum;
}

Then you can add the elements on the first and last rows like

int sum = sumArray(in[0]) + sumArray(in[in.length - 1]);

And then the outer elements from the other rows with an additional (non-nested) loop like

for (int i = 1; i < in.length - 1; i++) {
    sum += in[i][0] + in[i][in[i].length - 1];
}

Or, in Java 8+, you might eliminate the extra method and the explicit loop and do it with one statement like

int sum = IntStream.of(in[0]).sum() //
        + IntStream.of(in[in.length - 1]).sum() //
        + IntStream.range(1, in.length - 1).map(i -> {
            return in[i][0] + in[i][in[i].length - 1];
        }).sum();

Upvotes: 1

Related Questions