1
votes

I need to determine whether or not a magic square is magic or not. I need to compare the sum for every row and the sum with every column and then compare those with the sum of the diagonal and then with the sum of the other matrix.

I have calculated the sum for every row and for every column including with the two diagonals.

I need it to return true if the square is magic (all rows, cols, and diagonals have same sum false otherwise)

How would i set up this code?

1
And the question is? - Jean Logeart
I don't get it, you claim to have calculated required sums, so you should have all required informations to determine if square is magic or not. What is problem you are facing now? You just need to check if all sums are same. - Pshemo
why can't you do something like return ((a == b && c == d) && b == c)? - MZimmerman6

1 Answers

1
votes
public class MatrixService {

public static boolean isMagicSquare(int[][] arr) {
    final int size = arr.length;
    final int totalSize = size * size;
    final int magicNumber = (size * size * (size * size + 1) / 2) / size;
    int sumOfRow = 0, sumOfColoumns = 0, sumOfPrimaryDiagonal = 0, sumOfSecondaryDiagonal = 0;
    boolean[] flag= new boolean[size * size];

    for (int row = 0; row < size; row++) {
        sumOfRow = 0;
        sumOfColoumns = 0;
        for (int col = 0; col < size; col++) {
            if (arr[row][col] < 1 || arr[row][col] > totalSize) {
                return false;
            }
            if (flag[arr[row][col] - 1] == true) {
                return false;
            }
            flag[arr[row][col] - 1] = true;
            sumOfRow += arr[row][col];
            sumOfColoumns += arr[col][row];
        }
        sumOfPrimaryDiagonal += arr[row][row];
        sumOfSecondaryDiagonal += arr[row][n-row-1];

        if (sumOfRow != magicNumber || sumOfColoumns != magicNumber) {
            return false;
        }

        if (sumOfPrimaryDiagonal != magicNumber || sumOfSecondaryDiagonal != magicNumber) {
            return false;
        }

        return true;
    }

    public static void main(String []args){
        int[][] a ={{4,9,2},
                {3,5,7},
                {8,1,6}};
        System.out.println(isMagicSquare(a));
   }
}