【问题标题】:How to sum two 2D arrays elementwise?如何按元素对两个二维数组求和?
【发布时间】:2021-01-30 08:51:00
【问题描述】:

我遇到了如何对两个二维数组元素求和的问题。我参考了另一篇文章: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();

我应该补充一点,最终目标是实现线程安全的并行流。

【问题讨论】:

    标签: java matrix multidimensional-array stream add


    【解决方案1】:

    这样做:它将适用于任何两个相同结构的 int 数组。基本上我只是迭代数组的长度,将各个单元格相加,然后先转换为单个数组,然后再转换为二维数组。

    • MapToObj 是必需的,因为第二个 IntStream 不是 int 而是流对象。

    • 那么我只需要一个map,因为我正在处理第二个IntStream,即ints

    • 所有这些都是用于获取数组值的简单索引。

    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));
    

    打印

    [[6, 8], [10, 12, 15], [7]]
    

    【讨论】:

      【解决方案2】:

      您可以按元素对多个不同大小的锯齿状二维数组进行求和,如下所示:

      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][]);
      }
      

      另见:Sum of 2 different 2D arrays

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多