【问题标题】:Code is not giving expected result in sudoku代码在数独中没有给出预期的结果
【发布时间】:2014-09-17 03:57:48
【问题描述】:

我已经编写了匹配二维数组的基本逻辑,但结果有点意外

if(mat1[i][j] == mat2[i][j]) //what this line do

public static final int[][] n_1 = {{10,12,6,-1,-1},{-1,0,8,2,-1},{0,0,0,-1,0},{0,0,0,0,0},{-1,9,0,0,-1}};
public static final int[][] n_2 = {{13,-1,9,6,0},{0,-1,-1,0,0},{0,0,0,0,0},{-1,4,7,-1,0},{-1,2,8,0,0}};
public static final int[][] n_3 = {{-1,0,0,-1,-1},{0,0,0,11,-1},{0,0,0,5,-1},{8,0,0,0,13},{10,-1,6,4,0}};
public static final int[][] n_4 = {{10,8,0,1,-1},{13,0,0,3,-1},{0,0,0,-1,-1},{0,0,5,0,-1},{7,0,0,0,-1}};
public static final int[][] n_5 = {{-1,0,0,6,0},{-1,0,0,0,0},{12,0,5,-1,0},{0,0,3,-1,0},{4,-1,-1,-1,1}};

public static int[][][] arrayFive = {n_1,n_2,n_3,n_4,n_5};  
public static int [][] return5(){
    Random r = new Random();
    return arrayFive[r.nextInt(arrayFive.length)];
}

public boolean checkEqual(int[][] mat1,int[][] mat2){
    boolean b = true;
    for(int i = 0;i<mat1.length;i++){
        for(int j=0;j<mat1.length;j++){
            if(mat1[i][j] == mat2[i][j]){
                b = b & true;
            }
            else{
                b = b &false;
            }
        }
    }
    return b;
}

【问题讨论】:

  • 哪行代码你没有得到?
  • @sᴜʀᴇsʜᴀᴛᴛᴀ if(mat1[i][j] == mat2[i][j])
  • if(mat1[i][j] == mat2[i][j]) 只是在进行 int 比较。如果 mat1 是 n_1 而 mat2 是 n_2 则循环只是检查是否 10 == 13、12 == -1 等等。
  • @Mann 这只是检查 mat 和 mat2 中的元素。顺便说一句,还有一个错字。
  • 第二个for循环的退出条件不应该是j&lt;mat1[i].length吗?

标签: java logic sudoku


【解决方案1】:

这一行:

        if (mat1[i][j] == mat2[i][j]) 

正在测试两个矩阵的对应元素是否具有相同的值。

在上下文中查看它:

        if(mat1[i][j] == mat2[i][j]){
            b = b & true;
        }
        else{
            b = b &false;
        }

这是一种相当麻烦的说法:

        if(mat1[i][j] != mat2[i][j]){
            b = false;
        }

但您可以将checkEqual 方法重写为:

public boolean checkEqual(int[][] mat1,int[][] mat2){
    for(int i = 0;i<mat1.length;i++){
        for(int j=0;j<mat1.length;j++){
            if(mat1[i][j] != mat2[i][j]){
                return false;
            }
        }
    }
    return true;
}

这在矩阵不相等的情况下要快得多。

最后,值得注意的是,代码假设这两个矩阵是正方形的,并且它们具有相同的大小。如果其中任何一个假设不成立,则该方法将引发异常。

【讨论】:

  • 矩阵为正方形,大小相同。谢谢
  • @Mann - 是的,在这个例子中,他们显然是。但如果此代码用于更大的应用程序,则该假设可能并不总是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
相关资源
最近更新 更多