开发者

Arrays problems in Java

I'm trying to write some code that gets matrix 9X9 and two numbers: row- represents number of a row and col- represents number of a column. Zone is little matrix 3X3. the big matrix contains 9 little matrices of 3X3. the method is boolean: and it is outputs true if there are no equal numbers in the cells of little matrix 3X3 that will be located by the row and col numbers. ( the numbers can be from 1 'till 9).

I'm using a boolean array, and take advantage of its index, whenever I meet a number, I update his index-cell in the boolean array, and if I 开发者_如何学Gomeet true twice I retuen False. There can be a situation when the cell is empty, whenever it happens the cell contains the value "-1". The code the compiles but does not do the work. As you can see, I'm searching for the bounds with mod 3.

Can someone recognize a bug?

public static boolean isZoneValid(int row, int col, int[][] matrix) {
    int fromrow = row - (row % 3);
    int fromcol = col - (col % 3);
    boolean[] ind = new boolean[9];
    Arrays.fill(ind, false);
    for (int i = fromrow; i < fromrow + 3; i++) {
        for (int j = fromcol; j < fromcol + 3; j++) {
            if (matrix[i][j] != -1) {
                if (ind[(matrix[i][j])-1] == true) {
                    return false;
                } else {
                    ind[(matrix[i][j]) - 1] = true;
                }

            }
        }

    }
    return true;
}


I wrote this simple test and it passes all of them. Can you provide a test it does not pass?

int[][] a = {{7, 8, 9}, {1, 2, 3}, {4, 5, 6}};
if (!isZoneValid(0, 0, a)) throw new AssertionError("a");
int[][] b = {{-1, -1, 9}, {-1, 2, 3}, {9, 5, 6}};
if (isZoneValid(0, 0, b)) throw new AssertionError("b");
int[][] c = {{-1, -1, -1}, {-1, -1, -1}, {-1, -1, -1}};
if (!isZoneValid(0, 0, c)) throw new AssertionError("c");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜