0

I am running into trouble with how to sum two 2D arrays elementwise. I have referenced another post: Java 8 Stream and operation on arrays, and understand how to do this with two 1D arrays but how do you now progress through the rows of a 2D array?

//in this example a[] and b[] are Square matrices
int[] A = [n][n]
int[] B = [n][n]

int[] result = new int[A.length][A[0].length];

//I know this only adds the first rows together.
//How do I now iterate through the rows to sum the entire matrix elementwise
result[0] = IntStream.range(0, A.length).map(i -> A[0][i] + B[0][i]).toArray();

I should add that the end goal is to do a threadsafe parallel stream implementation.

Community
  • 1
  • 1
Jeff O
  • 11
  • 3

2 Answers2

0

Do it like this: It will work on any two int arrays of the same structure. Basically I just iterate the length of the arrays, sum the individual cells, and convert first to a single array and then those to a 2D array.

  • the MapToObj is necessary because the second IntStream is not an int but a stream object.

  • then all I need is a map as I am acting on the second IntStream which are ints.

  • All of these are simply indices that are used to get the array values.

int[][] a = { { 1, 2 }, { 3, 4, 5 }, {3} };
int[][] b = { { 5, 6 }, { 7, 8, 10 }, {4} };

int[][] sum = IntStream.range(0, a.length)
        .mapToObj(r -> IntStream.range(0, a[r].length)
                .map(c -> a[r][c] + b[r][c]).toArray())
        .toArray(int[][]::new);

System.out.println(Arrays.deepToString(sum));

Prints

[[6, 8], [10, 12, 15], [7]]
WJS
  • 36,363
  • 4
  • 24
  • 39
0

You can element-wise sum multiple jagged 2D arrays of different sizes as follows:

public static void main(String[] args) {
    int[][] a = {{3, 3, 3}, {3, 3, 3}, {3, 3, 3}};
    int[][] b = {{2}, {2}};
    int[][] c = {{1, 1}, {1, 1}, {1, 1, 1, 1}};

    int[][] s = sumArrays(a, b, c);

    System.out.println(Arrays.deepToString(s));
    // [[6, 4, 3], [6, 4, 3], [4, 4, 4, 1]]
}
public static int[][] sumArrays(int[][]... arrays) {
    return Arrays.stream(arrays)
          // sequential summation of array pairs
          .reduce((arr1, arr2) -> IntStream
              // iterate over the indexes of the rows of the max array
              .range(0, Math.max(arr1.length, arr2.length))
              // summation of two rows
              .mapToObj(i -> {
                  // at least one row should be present
                  if (arr1.length <= i)
                    return arr2[i];
                  else if (arr2.length <= i)
                    return arr1[i];
                  else // both rows are present
                    return IntStream
                      // iterate over the indices of the max row
                      .range(0, Math.max(arr1[i].length, arr2[i].length))
                      // the sum of two elements if present, or 0 otherwise
                      .map(j -> (arr1[i].length <= j ? 0 : arr1[i][j])
                              + (arr2[i].length <= j ? 0 : arr2[i][j]))
                      // cumulative row
                      .toArray();
              }) // cumulative array
              .toArray(int[][]::new))
          // or an empty array otherwise
          .orElse(new int[0][]);
}

See also: Sum of 2 different 2D arrays