我如何在2d数组中添加值?

时间:2014-09-18 02:30:08

标签: java methods multidimensional-array

所以我想创建一个程序,根据数组的值打印true或false。如果2d数组(行和列)中的值均等于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;

}

1 个答案:

答案 0 :(得分:0)

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

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;
}