如何在二维数组的一列中添加所有元素?

How to add all elements in a column of a two-dimensional array?

提问人:andrewc2023 提问时间:11/3/2023 最后编辑:Rifat Rubayatul Islamandrewc2023 更新时间:11/6/2023 访问量:53

问:

我正在寻找一种方法来添加具有不同长度数组的二维数组列中的所有元素。我快到了,但我不明白为什么程序突然做似乎违背了代码指示的事情。显然,它只是在做代码告诉它做的事情,但我无法确切地辨别出什么以及为什么。感谢您的帮助。

public class Main {
    public static void main(String[] args) {
        
        int[][] data = { {3, 2, 5},
                         {1, 4, 4, 8, 13},
                         {9, 1, 0, 2},
                         {0, 2, 6, 3, -1, -8} };
        
        int total = 0;
        int tick = 4;
        int row = 0;
        
        for (int col = 0; col != 5; col++) {
            for (int num = 0; num < data.length; num++) {
                if (col != 0 && data[row].length<col+1){
                    row++; //checks to see whether or not the column
                           // num is in range of the subarray
                }
                
                total += data[row][col];
                
                if (row == tick-1) {
                    System.out.println(total);
                }
                row++;
                
                if (row == tick) { //stops row from going over max
                    row = 0;
                    total = 0;
                }
            }
        }
    }
}
Java 多维数组

评论

0赞 Andrew S 11/4/2023
为什么要遍历所有列?感兴趣的列应该是要求和的任何列的固定值,并且只需要遍历行。(同时检查当前行的长度是否不超过感兴趣的列。这可能会有所帮助。

答:

0赞 saurabh kumar 11/4/2023 #1

该错误存在于跳过列数少于当前列号的行的逻辑中。

在第 5 次迭代中,当跳过行时是这样工作的col = 4

Iteration for the inner for loop when col 4
num goes from 0 .. 3

Iteration 1 (num = 0)
[row = 0]
Row 0 : Size [3] Skip by doing row++
[row = 1]
Do logic of adding number from Row 1 into total, row++
[row = 2]

Iteration 2 (num = 1)
[row = 2]
Row 2 : Size [4] Skip by doing row++
[row = 3]
Do logic of adding number from Row 3 into total, row++
[row = 4]
Logic to reset row and total get triggered resetting both to 0

正如你所看到的,你勾选休息发生在第二次迭代本身,然后内部循环再运行 2 次,将错误的值加回你的总数中。

更好的方法是维护一个输出数组,该数组保存列总和

public class Main {

  public static void main(String[] args)
      throws Exception {
    int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };

    ArrayList<Integer> columnWiseSum = new ArrayList<>();

    for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
      int[] row = data[rowIndex];
      for (int colIndex = 0; colIndex < row.length; colIndex++) {
        // Insert a column into the output list if it does not exist
        if (columnWiseSum.size() - 1 < colIndex) {
          columnWiseSum.add(0);
        }

        int cellValue = data[rowIndex][colIndex];
        
        // Add the value of this cell into the output
        columnWiseSum.set(colIndex, columnWiseSum.get(colIndex) + cellValue);
      }
    }

    System.out.println(columnWiseSum);
  }
}
0赞 Lironz 11/4/2023 #2

外循环有条件,这意味着只要 col 不等于 ,外循环就会运行。此条件假定二维数组中始终存在列,当子数组具有不同长度时,情况可能并非如此。col != 555

评论

0赞 Community 11/4/2023
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。
0赞 Reilas 11/4/2023 #3

"...我正在寻找一种方法来添加具有不同长度数组的二维数组列中的所有元素。..."

这种类型的阵列通常称为锯齿状阵列”。

下面是一个示例。
遍历数据,检查每个子数组中是否有第 n 个元素,并在适用时递增 x

当 n 为 5 时,这将返回 −8,当 n4,这将返回 12

int columnSum(int n, int[][] data) {
    int x = 0;
    for (int[] a : data) if (n < a.length) x += a[n];
    return x;
}

或者,使用

int columnSum(int n, int[][] data) {
    return Stream.of(data)
                 .filter(x -> n < x.length)
                 .mapToInt(x -> x[n])
                 .sum();
}

"...我快到了,但我不明白为什么程序突然做似乎违背了代码指示的事情。..."

这种努力是有效的,通常使用双循环来遍历二维数组
虽然,在这种情况下,从技术上讲,您只能访问单个维度,因此请使用单个循环