Advertisement
fosterbl

isMagicSquare Solution

Mar 3rd, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. public boolean isMagicSquare( int[][] arr ){
  2.     //empty is a magic square
  3.     if( arr.length == 0 ) return true;
  4.    
  5.     //check all rows have same number of columns as the number of rows
  6.     for( int r = 0; r < arr.length; r++){
  7.         if( arr.length != arr[r].length ) return false;
  8.     }
  9.    
  10.     //rows
  11.     int[] rowSums = new int[arr.length];
  12.     for(int r = 0; r < arr.length; r++){
  13.         for(int c = 0; c < arr[0].length; c++){
  14.             rowSums[r] += arr[r][c];//store the sum of each row in the 1D array
  15.         }
  16.     }
  17.     for(int r = 0; r < rowSums.length - 1; r++){
  18.         if( rowSums[r] != rowSums[r+1] ) return false;//if any row sums are not equal, return false
  19.     }
  20.    
  21.     //columns
  22.     int[] colSums = new int[arr[0].length];
  23.     for(int c = 0; c < arr[0].length; c++){
  24.         for(int r = 0; r < arr.length; r++){
  25.             colSums[c] += arr[r][c];//store the sum of each col in the 1D array
  26.         }
  27.     }
  28.     for(int c = 0; c < colSums.length - 1; c++){
  29.         if( colSums[c] != colSums[c+1] ) return false;//if any col sums are not equal, return false
  30.     }
  31.    
  32.     //diagonals
  33.     //left to right
  34.     int leftDiagSum = 0;
  35.     for( int rowAndCol = 0; rowAndCol < arr.length; rowAndCol++ ){
  36.         leftDiagSum += arr[rowAndCol][rowAndCol];
  37.     }
  38.    
  39.     //right to left
  40.     int rightDiagSum = 0;
  41.     int x = arr.length - 1;
  42.     for( int rowAndCol = 0; rowAndCol < arr.length; rowAndCol++ ){
  43.         rightDiagSum += arr[rowAndCol][x - rowAndCol];
  44.     }
  45.     if( leftDiagSum != rightDiagSum ) return false;
  46.    
  47.     return true;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement