-7

I have written the basic logic to match 2D array, but the result are bit unexpected

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;
}
Maveňツ
  • 1
  • 12
  • 50
  • 89

1 Answers1

2

This line:

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

is testing to see if the corresponding elements of the 2 matrices have the same value.

Looking at it in context:

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

is a rather cumbersome way of saying this:

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

But you could rewrite the checkEqual method to this:

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

which is a whole lot faster in the case where the matrices are not equal.

Finally, it is worth noting that the code assumes that the two matrices are square, and they have the same size. If either of those assumptions is false, the method will throw an exception.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216