简体   繁体   English

如何按元素对两个二维数组求和?

[英]How to sum two 2D arrays elementwise?

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?我参考了另一篇文章: Java 8 Stream and operation on arrays ,并了解如何使用两个一维数组执行此操作,但是您现在如何处理二维数组的行?

//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.我应该补充一点,最终目标是做一个线程安全的并行流实现。

Do it like this: It will work on any two int arrays of the same structure.这样做:它可以处理相同结构的任何两个 int 数组。 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. MapToObj是必要的,因为第二个 IntStream 不是 int 而是流对象。

  • then all I need is a map as I am acting on the second IntStream which are ints .那么我所需要的只是一张map因为我正在处理第二个IntStreamints

  • 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]]

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另请参阅: 2 个不同二维数组的总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM