Skip to main content

Java - Magic Square

MAGIC SQUARE - It is a nxn square grid where sum of elements of every row, every column and both the diagonals results into a same value.

The sum of elements is called magic constant. It can be calculated using this formula-
                                                            magic constant=n*(n^2+1)/2
In this article, we are gonna make a program to check if a square grid of size nxn is a magic square or not.
An array is a magic square if it follows following conditions-
  • It must be a square array
  • Sum of elements of every row must be equal to magic constant
  • Sum of elements of  every column must be equal to magic constant
  • Sum of elements of  both the diagonals must be equal to magic constant
  • Each value must be between 1 and n^2
  • Array must have distinct values
1. Create a new java class with name MagicSquare and add following code
public class MagicSquare {

        public static void main(String[] args) {
                
                // Test samples
                System.out.println("TEST CASE 1 - NOT A MAGIC SQUARE\n");
                int[][] array={{23,6,19,2,15},{11,24,7,20,3},{4,12,25,8,16},{17,5,13,21,9},{10,18,1,14,22}};
                check(array);
                
                System.out.println("\nTEST CASE 2 - A MAGIC SQUARE\n");
                int[][] array1={{8,1,6},{3,5,7},{4,9,2}};
                check(array1);
        }
        
        public static void check(int[][] array){
                boolean overall;
                boolean rows,columns,diagonals;
                boolean values;
                int magicConstant;
                
                if(!isSquare(array)){
                        System.out.println("The array is not square");
                        overall=false;
                }else{
                        magicConstant=magicConstant(array);
                        System.out.println("The magic constant is "+magicConstant);
                        
                        //Call all check methods
                        rows=checkRows(array,magicConstant);
                        columns=checkColumns(array,magicConstant);
                        values=checkValues(array,magicConstant);
                        diagonals=checkDiagonals(array,magicConstant);
                        
                        //find overall boolean result
                        overall=rows&&columns&&values&&diagonals;
                }
                
                // If true, given array is a magic square else not
                if(overall){
                        System.out.println("This is a magic square");
                }else{
                        System.out.println("This is not a magic square");
                }
        }

        // This function calculates magic constant and returns the value
        private static int magicConstant(int[][] array) {
                int magicConstant=0;
                int length=array.length;
                magicConstant=length*((length*length)+1)/2;
                return magicConstant;
        }

        // This function checks if the given array is a square grid
        private static boolean isSquare(int[][] array) {
                if(array.length==array[0].length){
                        return true;
                }
                return false;
        }
        
        //Check diagonals method
        public static boolean checkDiagonals(int[][] square,int magicConstant){
                int length,wrong,sum;
                length=square.length;
                int lastCol=length-1;
                wrong=0;
                sum=0;
                
                //Diagonal 1 from (0,0) to (n-1,n-1)
                //diagonals value can be found using one loop, 
                //because diagonals values are present at (0,0) (1,1), (2,2), (3,3), (4,4) so on
                for(int row=0;row<length;row++){        
                        sum+=square[row][row];  
                }
                
                // If sum is not equal to magicConstant, increment wrong by 1
                if(sum!=magicConstant){
                        wrong++;
                }
                
                // Re-set sum to 0, to check diagonal sum for diagonal 2
                sum=0;
                
                //Diagonal 2 from (0,n-1) to (n-1,0)
                //diagonals value can be found using one loop, 
                //because diagonals values are present at (0,2) (1,1), (2,0) for array of length 3
                for(int row=0;row<length;row++){        
                        sum+=square[row][lastCol];      
                        lastCol-=1;
                }
                // If sum is not equal to magicConstant, increment wrong by 1
                if(sum!=magicConstant){
                        wrong++;
                }
                System.out.println("There were "+wrong+" invalid diagonals.");
                return wrong==0;
        }
        
        
        public static boolean checkRows(int[][] square,int magicConstant){
                int length,wrong,sum;
                length=square.length;
                
                wrong=0;
                
                // Iterate loop to get sum of every row
                // Re-set sum to 0 after inner for loop
                for(int row=0;row<length;row++){
                        sum=0;
                        for(int col=0;col<length;col++){
                                sum+=square[row][col];
                        }
                        // If sum is not equal to magicConstant, increment wrong by 1
                        if(sum!=magicConstant){
                                wrong++;
                        }
                }
                
                System.out.println("There were "+wrong+" invalid rows.");
                return wrong==0;
        }
        
        public static boolean checkColumns(int[][] square,int magicConstant){
                int length,wrong,sum;
                length=square.length;
                
                wrong=0;
                
                // Iterate loop to get sum of every column
                // Re-set sum to 0 after inner for loop
                for(int col=0;col<length;col++){
                        sum=0;
                        for(int row=0;row<length;row++){
                                sum+=square[row][col];
                        }
                        // If sum is not equal to magicConstant, increment wrong by 1
                        if(sum!=magicConstant){
                                wrong++;
                        }
                }
                
                System.out.println("There were "+wrong+" invalid columns.");
                return wrong==0;
        }
        
        public static boolean checkValues(int[][] square,int magicConstant){
                int[] counts;
                int length,wrong;
                length=square.length;
                
                wrong=0;
                
                // Array to keep occurrence of every element in array
                counts=new int[length*length+1];
                
                // Iterate loop to check if values in array are valid or not
                // Values are invalid - 
                // If it is less than 1 or greater than n*n (square of size of array)
                for(int row=0;row<length;row++){
                        for(int col=0;col<length;col++){
                                if(square[row][col]<1 || square[row][col]>length*length){
                                        wrong++;
                                }else{
                                        counts[square[row][col]]++;
                                }
                        }
                }
                
                // An array cannot be a magic square if it doesn't contain distinct values
                // Iterate loop over elements of count array
                // If value at index i is > 1, increment wrong by 1
                for(int i=1;i<=length*length;i++){
                        if(counts[i]>1){
                                wrong++;
                        }
                }
                
                System.out.println("There were "+wrong+" invalid values.");
                return wrong==0;        
        }
}
2. Run the program
Output-



Comments

Popular Posts