我已经编写了匹配2D数组的基本逻辑,但结果有些意外
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;
}
答案 0 :(得分:3)
这一行:
if (mat1[i][j] == mat2[i][j])
正在测试以查看2个矩阵的相应元素是否具有相同的值。
在上下文中查看:
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;
}
在矩阵不相等的情况下,速度要快得多。
最后,值得注意的是,代码假设两个矩阵是正方形的,并且它们具有相同的大小。如果其中任何一个假设为假,则该方法将抛出异常。