【问题标题】:Calculating the sum for each array column计算每个数组列的总和
【发布时间】:2021-03-31 10:44:45
【问题描述】:

我有一个二维数组data,作为示例,我选择了这些数字:

int[][] data = {
        {1, 2, 3, 4},
        {1, 2, 3, 4},
        {1, 2, 3, 4}};

对于每一列,我想将数字的总和相加并将它们保存在单独的整数中。 这是我正在寻找的结果:

c_zero = 3;
c_one = 6;
c_two = 9;
c_three = 12;

这是我到目前为止的代码:

int c_zero = 0;
int c_one = 0;
int c_two = 0;
int c_three = 0;

for (int a = 0; a < data.length; a++) {
    for (int b = 0; b < data.length; b++) {
        for (int[] row : data)
            for (int value : row) {
                if (int[] row == 0) { //this does not work
                    c_zero += value;
                }
                if (int[] row == 1) { //this does not work
                    c_one += value;
                }
                ...
            }
    }
}

如何获取特定行中每一行的值?

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    我会创建一个一维整数数组并用它来存储每一列的运行总和:

    int[][] data = {{1,2,3,4},
                    {1,2,3,4},
                    {1,2,3,4}};
    int[] colSums = new int[data[0].length];
    
    for (int r=0; r < data.length; ++r) {
        for (int c=0; c < data[r].length; ++c) {
            colSums[c] += data[r][c];
        }
    }
    
    System.out.println(Arrays.toString(colSums)); // [3, 6, 9, 12]
    

    【讨论】:

      【解决方案2】:

      使用Java 8,您可以将reduce 方法应用于二维数组的行上的stream,以对中的元素求和并生成sums 的一维数组。

      // array must not be rectangular
      int[][] data = {
              {1, 2, 3, 4},
              {1, 2, 3, 4},
              {1, 2, 3, 4, 5}};
      
      int[] sum = Arrays.stream(data)
              // sequentially summation of
              // the elements of two rows
              .reduce((row1, row2) -> IntStream
                      // iterating over the indexes of the largest row
                      .range(0, Math.max(row1.length, row2.length))
                      // sum the elements, if any, or 0 otherwise
                      .map(i -> (i < row1.length ? row1[i] : 0)
                              + (i < row2.length ? row2[i] : 0))
                      // array of sums by column
                      .toArray())
              .orElse(null);
      
      // output of an array of sums
      System.out.println(Arrays.toString(sum));
      // [3, 6, 9, 12, 5]
      
      // output by columns
      IntStream.range(0, sum.length)
              .mapToObj(i -> "Column " + i + " sum: " + sum[i])
              .forEach(System.out::println);
      //Column 0 sum: 3
      //Column 1 sum: 6
      //Column 2 sum: 9
      //Column 3 sum: 12
      //Column 4 sum: 5
      

      另见:
      Adding up all the elements of each column in a 2d array
      How to create all permutations of tuples without mixing them?

      【讨论】:

        猜你喜欢
        • 2014-06-23
        • 2012-10-18
        • 2021-05-23
        • 2017-07-15
        • 1970-01-01
        • 2015-09-20
        • 2021-09-05
        • 2022-12-30
        • 1970-01-01
        相关资源
        最近更新 更多