如何对两个二维数组逐元素进行求和?

huangapple go评论65阅读模式
英文:

How to sum two 2D arrays elementwise?

问题

我在如何逐元素求和两个二维数组方面遇到了问题。我参考了另一篇帖子:Java 8 中的流和数组操作,并了解了如何在两个一维数组中进行操作,但如何在二维数组的行中进行迭代呢?

//在这个例子中,a[] 和 b[] 都是方阵
int[][] A = new int[n][n];
int[][] B = new int[n][n];

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

//我知道这只是将第一行相加。
//那么我如何通过迭代行来逐元素求和整个矩阵呢?
for (int i = 0; i < A.length; i++) {
    result[i] = IntStream.range(0, A[i].length)
                        .map(j -> A[i][j] + B[i][j])
                        .toArray();
}

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

英文:

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 -&gt; A[0][i] + B[0][i]).toArray();

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

答案1

得分: 0

像这样做:它适用于任何具有相同结构的两个整数数组。基本上我只是迭代数组的长度,对每个单元格求和,然后先转换为单个数组,然后再转换为2D数组。

  • MapToObj 是必要的,因为第二个 IntStream 不是整数,而是一个流对象。
  • 然后我只需要一个 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]]
英文:

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 -&gt; IntStream.range(0, a[r].length)
				.map(c -&gt; a[r][c] + b[r][c]).toArray())
		.toArray(int[][]::new);

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

Prints

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

答案2

得分: 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)
          // 顺序求和数组对
          .reduce((arr1, arr2) -> IntStream
              // 遍历最大数组行的索引
              .range(0, Math.max(arr1.length, arr2.length))
              // 两行求和
              .mapToObj(i -> {
                  // 至少应存在一行
                  if (arr1.length <= i)
                    return arr2[i];
                  else if (arr2.length <= i)
                    return arr1[i];
                  else // 两行都存在
                    return IntStream
                      // 遍历最大行的索引
                      .range(0, Math.max(arr1[i].length, arr2[i].length))
                      // 如果存在则求两个元素的和,否则为0
                      .map(j -> (arr1[i].length <= j ? 0 : arr1[i][j])
                              + (arr2[i].length <= j ? 0 : arr2[i][j]))
                      // 累积行
                      .toArray();
              }) // 累积数组
              .toArray(int[][]::new))
          // 否则返回空数组
          .orElse(new int[0][]);
}

<sup>参见:两个不同的二维数组的求和</sup>

英文:

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) -&gt; 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 -&gt; {
                  // at least one row should be present
                  if (arr1.length &lt;= i)
                    return arr2[i];
                  else if (arr2.length &lt;= 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 -&gt; (arr1[i].length &lt;= j ? 0 : arr1[i][j])
                              + (arr2[i].length &lt;= j ? 0 : arr2[i][j]))
                      // cumulative row
                      .toArray();
              }) // cumulative array
              .toArray(int[][]::new))
          // or an empty array otherwise
          .orElse(new int[0][]);
}

<sup>See also: Sum of 2 different 2D arrays</sup>

huangapple
  • 本文由 发表于 2020年10月16日 03:59:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64378873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定