0

Here is a subcode of calculating if a given matrix is a magic square. I'm only confused with the test[element -1] that is duplicated and have two different returns.

public static boolean testNormal(int[][] matrix, int dim){

    int magicConstant = dim * (dim * dim +1) / 2;

    // checks if all the numbers are present
    // the default value is false
    boolean[] test = new boolean[dim*dim];
    int max = dim*dim;
    int element;
    for (int row = 0; row < dim; row++){
        for (int col = 0; col < dim; col++){
            element = matrix[row][col];
            if ((element > max)|| (element <= 0))
                return false;
            if (test[element -1])
                return false;
            test[element -1] = true;
        }
    }
matt
  • 10,892
  • 3
  • 22
  • 34

1 Answers1

1

The code is not formatted very nicely to my taste:

for (int col = 0; col < dim; col++){
    element = matrix[row][col];
    if ((element > max)|| (element <= 0)) {
        return false;
    }
    if (test[element -1]) {
        return false;
    }
    test[element -1] = true;
}

Writing it like this should make it a bit clearer.

So to explain if (test[element -1]) gets the boolean at position 'element - 1' from the test array, if it evaluates to true we enter the if statement and return false. The next line is not executes since we return.

If it evaluates to false we do not enter the if statement and the value of test[element - 1] is set to true.

So it is not duplication, the only thing the instances share is that they access the same position in the array. The first instance gets and evaluates something from the test array and the second instance sets something in the test array.

Snagtz
  • 118
  • 6