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

问题描述 投票:0回答:2

我在如何按元素求和两个二维数组方面遇到了麻烦。我引用了另一篇文章:Java 8 Stream 和数组操作,并了解如何使用两个一维数组执行此操作,但现在如何处理二维数组的行?

//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 java-stream addition
2个回答
0
投票

这样做:它将适用于任意两个具有相同结构的 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]]

0
投票

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

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

另请参阅:2 个不同二维数组的总和

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.