Search code examples
javamagic-square

Magic Square final value always true


For class we have to do a magic square. I got my code somewhat working but it does multiple squares and the final one always returns 0, Here is how a magic square works.enter image description here

Here is how I check

  public int downDiagSum() {
int sum = 0;
for(int r = 0; r < grid.length; r++){
    for(int c = 0; c < grid.length; c++){
        sum += grid[r][c];
    }
}
return sum;



 public int upDiagSum() {
int sum = 0;
for(int r = grid.length - 1; r >= 0; r--){
    for(int c = 0; c < grid.length; c++){
        sum += grid[r][c];
    }
}
return sum;



 public int colSum(int col) {
int sum1 = 0;
for(int r = 0; r < grid[0].length; r++){
    sum1 += grid[r][col];
}
return sum1;

public int rowSum(int row) {
int sum2 = 0;
for(int r = 0; r < grid[0].length; r++){
    sum += grid[row][r];
  }
return sum2;


 public boolean isMagicSquare() {
int num = rowSum(0);
boolean isEqual = false;
if(downDiagSum() == upDiagSum()){
    //row check
    for(int r = 0; r < grid.length; r++){
        if(rowSum(r) == num){
            isEqual = true;
        }
      }
    //column check
    for(int r = 0; r < grid.length; r++){
        for(int c = grid.length - 1; c >= 0; c--){
            if(colSum(c) == num){
                isEqual = true;
            }
        }
    }
}
return isEqual;}

The code mostly works but if I have a series it always returns true for some reason. The number set below is supposed to return false but returns true

6 32 2 34 35 1
7 11 27 28 8 30
19 14 16 15 23 24
18 20 22 21 17 13
25 29 10 9 26 12
36 5 33 4 3 31

Sorry for bad formatting i'm still very new to site. Thanks, Garrows


Solution

  • In both of your loops you are checking every row and every column. And your logic says when one row or one column sum is equal to the sum of first row (and this includes the sum of the very first row!!!), your variable isTrue becomes true (forever)! So, you should reverse your logic...

    Pseudo algorithm:

    isTrue = true
    int magicSum = sumOfFirstDiagonal
    if (magicSum != sumOfSecondDiagonal) {isTrue = false; return}
    for each row
        if (magicSum != sumOfRow) {isTrue = false; return}    
    for each column
        if (magicSum != sumOfColumn) {isTrue = false; return} 
    

    And here is correct way to calculate sum of diagonals:

    public static int diagSumTwo() {
        int sum = 0;
        for (int r = 0; r < grid.length; r++) {
            sum += grid[r][r];
        }
        return sum;
    }
    
    public static int diagSumOne() {
        int sum = 0;
        for (int r = grid.length - 1; r >= 0; r--) {
            sum += grid[r][grid.length - 1 - r];
        }
        return sum;
    }