0

I have a 2d-array data, as an example I choose those numbers:

int[][] data = {
        {1, 2, 3, 4},
        {1, 2, 3, 4},
        {1, 2, 3, 4}};

For each column I want to add the sum of numbers together and save them in seperate integers. This is the result im looking for:

c_zero = 3;
c_one = 6;
c_two = 9;
c_three = 12;

This is the code I have thus far:

int c_zero = 0;
int c_one = 0;
int c_two = 0;
int c_three = 0;

for (int a = 0; a < data.length; a++) {
    for (int b = 0; b < data.length; b++) {
        for (int[] row : data)
            for (int value : row) {
                if (int[] row == 0) { //this does not work
                    c_zero += value;
                }
                if (int[] row == 1) { //this does not work
                    c_one += value;
                }
                ...
            }
    }
}

How can I get the values for each row in a specific row?

0

2 Answers 2

2

I would create a 1D integer array and use that to store the running sum for each column:

int[][] data = {{1,2,3,4},
                {1,2,3,4},
                {1,2,3,4}};
int[] colSums = new int[data[0].length];

for (int r=0; r < data.length; ++r) {
    for (int c=0; c < data[r].length; ++c) {
        colSums[c] += data[r][c];
    }
}

System.out.println(Arrays.toString(colSums)); // [3, 6, 9, 12]
Sign up to request clarification or add additional context in comments.

Comments

1

Using Java 8, you can apply the reduce method to the stream over the rows of a 2d array to sum the elements in the columns and produce a 1d array of sums.

// array must not be rectangular
int[][] data = {
        {1, 2, 3, 4},
        {1, 2, 3, 4},
        {1, 2, 3, 4, 5}};

int[] sum = Arrays.stream(data)
        // sequentially summation of
        // the elements of two rows
        .reduce((row1, row2) -> IntStream
                // iterating over the indexes of the largest row
                .range(0, Math.max(row1.length, row2.length))
                // sum the elements, if any, or 0 otherwise
                .map(i -> (i < row1.length ? row1[i] : 0)
                        + (i < row2.length ? row2[i] : 0))
                // array of sums by column
                .toArray())
        .orElse(null);

// output of an array of sums
System.out.println(Arrays.toString(sum));
// [3, 6, 9, 12, 5]
// output by columns
IntStream.range(0, sum.length)
        .mapToObj(i -> "Column " + i + " sum: " + sum[i])
        .forEach(System.out::println);
//Column 0 sum: 3
//Column 1 sum: 6
//Column 2 sum: 9
//Column 3 sum: 12
//Column 4 sum: 5

See also:
Adding up all the elements of each column in a 2d array
How to create all permutations of tuples without mixing them?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.