Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean isMagicSquare( int[][] arr ){
- //empty is a magic square
- if( arr.length == 0 ) return true;
- //check all rows have same number of columns as the number of rows
- for( int r = 0; r < arr.length; r++){
- if( arr.length != arr[r].length ) return false;
- }
- //rows
- int[] rowSums = new int[arr.length];
- for(int r = 0; r < arr.length; r++){
- for(int c = 0; c < arr[0].length; c++){
- rowSums[r] += arr[r][c];//store the sum of each row in the 1D array
- }
- }
- for(int r = 0; r < rowSums.length - 1; r++){
- if( rowSums[r] != rowSums[r+1] ) return false;//if any row sums are not equal, return false
- }
- //columns
- int[] colSums = new int[arr[0].length];
- for(int c = 0; c < arr[0].length; c++){
- for(int r = 0; r < arr.length; r++){
- colSums[c] += arr[r][c];//store the sum of each col in the 1D array
- }
- }
- for(int c = 0; c < colSums.length - 1; c++){
- if( colSums[c] != colSums[c+1] ) return false;//if any col sums are not equal, return false
- }
- //diagonals
- //left to right
- int leftDiagSum = 0;
- for( int rowAndCol = 0; rowAndCol < arr.length; rowAndCol++ ){
- leftDiagSum += arr[rowAndCol][rowAndCol];
- }
- //right to left
- int rightDiagSum = 0;
- int x = arr.length - 1;
- for( int rowAndCol = 0; rowAndCol < arr.length; rowAndCol++ ){
- rightDiagSum += arr[rowAndCol][x - rowAndCol];
- }
- if( leftDiagSum != rightDiagSum ) return false;
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement