Zubair Zubair - 25 days ago 9
Java Question

How do I find the sum of values for a multidimensional array and replace values of unused indexes?

I have 4x4 2D array that already has values in each index. I want to have a function that calculates the sum of a row/column of the array and store it at the first/final column and have the other indexes revert to 0.

This is what I have to render my array:

public static void print2Darray(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
System.out.print(numbers[i][j]);
System.out.print("\t");
}
System.out.println();
}
}


Which displays something like this:

10 15 30 40
15 5 8 2
20 2 4 2
1 4 5 0


Currently this is the function that I have:

public static void sumLeft(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i][0] = (numbers[i][0] + numbers[i][1] + numbers[i][2] + numbers[i][3]);
if (i == 3) {
numbers[0][1] = 0;
numbers[0][2] = 0;
numbers[0][3] = 0;
numbers[1][1] = 0;
numbers[1][2] = 0;
numbers[1][3] = 0;
numbers[2][1] = 0;
numbers[2][2] = 0;
numbers[2][3] = 0;
numbers[3][1] = 0;
numbers[3][2] = 0;
numbers[3][3] = 0;
}
}
}


Which does this:

95 0 0 0
30 0 0 0
28 0 0 0
10 0 0 0


I just want to find an algorithm that would do this without "cheating" or just hacking my way through it.

Answer Source

All you need to do is loop over the elements of the "row" array:

public static void sumLeft(int[][] numbers) {
    for (int i = 0; i < numbers.length; i++) {
        for (int j = 1; j < numbers[i].length; j++) {
            numbers[i][0] += numbers[i][j];
            numbers[i][j] = 0;
        }
    }
}