1

So I have this dummy 2D array:

int mat[][] = {
        {10, 20, 30, 40, 50, 60, 70, 80, 90},
        {15, 25, 35, 45},
        {27, 29, 37, 48},
        {32, 33, 39, 50, 51, 89}};

I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:

public void sum(int[][] array) {
    int count = 0;
    for (int rows = 0; rows < array.length; rows++) {
        for (int columns = 0; columns < array[rows].length; columns++) {
            System.out.print(array[rows][columns] + "\t");
            count += array[0][0];
        }
        System.out.println();
        System.out.println("total = " + count);
    }
}

Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?

Community
  • 1
  • 1
Fire assassin
  • 81
  • 1
  • 9

5 Answers5

1

Use an ArrayList to get the sum of all the columns.

public static void sum(int[][] array) {
    ArrayList<Integer> sums = new ArrayList<>();
    for (int row = 0; row < array.length; row++) {
        for (int column = 0; column < array[row].length; column++) {
            if (sums.size() <= column) {
                sums.add(column, 0);
            }
            int curVal = sums.get(column);
            sums.remove(column);
            sums.add(column, curVal + array[row][column]);
        }
    }
    for (int i = 0; i < sums.size(); i++) {
        System.out.println("Sum of column " + i + " = " + sums.get(i));
    }
}
Chamal Perera
  • 313
  • 1
  • 2
  • 10
1

One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.

public static void main(String[] args) {
    int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
            {15, 25, 35, 45},
            {27, 29, 37, 48},
            {32, 33, 39, 50, 51, 89},
    };

    // Find maximum possible length of sub array
    int maxLength = 0;
    for (int i = 0; i < mat.length; i++) {
        if (maxLength < mat[i].length)
            maxLength = mat[i].length;
    }

    for (int i = 0; i < maxLength; i++) {
        int sum = 0;
        for (int j = 0; j < mat.length; j++) {
            // Avoid if no value available for
            // ith column from this subarray
            if (i < mat[j].length)
                sum += mat[j][i];
        }
        System.out.println("Sum of Column " + i + " = " + sum);
    }
}
Community
  • 1
  • 1
pahan
  • 567
  • 1
  • 8
  • 22
0

…and the same with lambda:

int[] array = Arrays.stream(mat)
  .reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
      .map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
          : i < a1.length ? a1[i] : a2[i] ).toArray()).get();

gets the sums of each column in the int[] array:

[84, 107, 141, 183, 101, 149, 70, 80, 90]
Kaplan
  • 2,572
  • 13
  • 14
0

You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:

int[][] matrix = {
        {10, 20, 30, 40, 50, 60, 70, 80, 90},
        {15, 25, 35, 45},
        {27, 29, 37, 48},
        {32, 33, 39, 50, 51, 89}};

int[] arr = Arrays.stream(matrix)
        // summarize in pairs
        // the rows of the matrix
        .reduce((row1, row2) -> IntStream
                // iterate over the indices
                // from 0 to maximum row length
                .range(0, Math.max(row1.length, row2.length))
                // summarize in pairs the elements of two rows
                .map(i -> (i < row1.length ? row1[i] : 0) +
                        (i < row2.length ? row2[i] : 0))
                // an array of sums
                .toArray())
        // the resulting array
        .get();

System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]

See also:
Sum of 2 different 2d arrays
How to calculate the average value of each column in 2D array?

0

Here is one alternative.

The supplied data.

int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
        { 15, 25, 35, 45 }, { 27, 29, 37, 48 },
        { 32, 33, 39, 50, 51, 89 }, };

First, find the maximum length of the array in which to store the sum.

int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);

Allocate the new array to hold the sums.

int[] sums = new int[max];

Now just use the Arrays.setAll method to sum them, taking care
to not exceed the current array's length.

for (int[] arr : mat) {
    Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}

System.out.println(Arrays.toString(sums));

Prints

[84, 107, 141, 183, 101, 149, 70, 80, 90]
WJS
  • 36,363
  • 4
  • 24
  • 39