【问题标题】:how do i add up values in 2d arrays?如何将二维数组中的值相加?
【发布时间】:2014-09-18 02:30:08
【问题描述】:

所以我想创建一个程序,该程序将根据数组的值打印 true 或 false。如果二维数组(行和列)中的值都等于 15。那么行中的值等于 15,列中的值等于 15。到目前为止我的代码:

public static boolean isAmazingArray(int[][] array) {
    int rowTemp = 0;
    int colTemp = 0;
    for (int row = 0; row < array.length; row++) {
        for (int col = 0; col < array[0].length; col++) {
            rowTemp += array[row][0];
            colTemp += array[0][col];


        }
        if (rowTemp == 15 && colTemp == 15) {
            return true;
        }

    }
    return false;

}

【问题讨论】:

  • 快速澄清:我们正在检查每行和每列的总和是否等于15?
  • 什么不起作用?您为调试自己做了哪些努力?
  • 是的,我正在尝试检查每一行和每一列的总和,看看它是否等于 15。
  • @AlexisLeclerc 我仍然不确定如何很好地调试程序,需要一些帮助
  • 嗯,首先,什么不工作?

标签: java methods multidimensional-array


【解决方案1】:

Simple for 迭代可以做到这一点。然而,值得注意的是,这要求数组是非锯齿状的(对于范围内的所有 i,array[i].length == array[0].length)。如果不是这种情况,它可能仍然有效,但问题会变得更有趣......正在修复......

public static boolean isAmazingArray(int[][] array) {
    final int VALID_VAL = 15;
    //Check Rows - handle jagged rows without issue
    for (int[] row : array) {
        int a = 0;
        for(int i : row) {a += i;}
        if(a != VALID_VAL) return false; //Found a bad row
    }

    //Check Cols - handle jagged-ness by finding max length row first.
    int maxRowLength = 0;
    for(int[] i : array){
        maxRowLength = Math.max(maxRowLength, i.length);
    }
    //Init array to hold running sum for each column
    int[] colSums = new int[maxRowLength];
    for(int r = 0; r < array.length; r++){
        for(int c = 0; c < array[r].length; c++){
           //Add value to its corresponding column sum
           colSums[c] += array[r][c];
        }
    }

    for(int i : colSums){
        //Found bad column
        if(i != VALID_VAL) return false;
    }

    //No invalid rows/cols found
    return true;
}

【讨论】:

  • 如何在它检查列的部分下,在 for 循环中它说 int r = 0 然后 i
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 2023-02-25
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多