kmahadev

IsMagicSquare

Nov 16th, 2014
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.62 KB | None | 0 0
  1.  
  2. public class MagicSquare {
  3.  
  4.     public static void main(String[] args) {
  5.         // TODO Auto-generated method stub\
  6.         int[][] matrix = {{2,7,6},{9,5,1}, {4, 3, 8} };
  7.         boolean finale = isMagicSquare(matrix);
  8.         if(finale == true){
  9.             System.out.println("It is a Magic Square");
  10.         }
  11.             else {System.out.println("It is NOT a Magic Square");
  12.         }
  13.        
  14.     }//end main
  15.    
  16.     public static boolean isMagicSquare(int[][] a) {
  17.         boolean result1 = false, result2 = false;
  18.         int[] sumRows = new int[a.length];
  19.         int[] sumCols = new int[a.length];
  20.         int sumDiag1 = 0, sumDiag2 = 0;
  21.         //initialize sumRows and sumCols arrays with 0's
  22.         for(int r=0; r < a.length; r++) {
  23.             sumRows[r] = 0;
  24.             sumCols[r] = 0;        
  25.         }//end for
  26.        
  27.         for(int r=0; r < a.length; r++) {
  28.             for(int c=0; c < a.length; c++) {
  29.                 sumRows[r] += a[r][c];
  30.                 sumCols[c] += a[r][c];
  31.                 if(r == c){                
  32.                     sumDiag1 += a[r][c];
  33.                 }//end if
  34.             }//end for c
  35.         }//end for r
  36.         //loops for calculating sumDiag2
  37.         for(int c=a.length-1; c >= 0; c--){
  38.             for(int r=0; r < a.length; r++){
  39.                 if((r+c) == a.length-1) {
  40.                     sumDiag2 += a[c][r];                   
  41.                 }//end if
  42.             }//end r
  43.         }//end c
  44.         if (sumDiag1 == sumDiag2) { result1 = true; }
  45.        
  46.         //Check if the sum of rows and columns are equal
  47.         for(int r=0; r < a.length; r++) {
  48.             if(sumRows[r] != sumCols[r]) {             
  49.                 result2 = false;
  50.             }//end if          
  51.             else {
  52.                 result2 = true;            
  53.             }
  54.         }//end for
  55.        
  56.         //then if all the results are true, it is a magic square
  57.         if(result1 && result2){
  58.             return true;
  59.         }
  60.         else { //it is not a magic square
  61.             return false;
  62.         }
  63.            
  64.     }//end isMagicSquare()
  65.  
  66. }//end class
Advertisement
Add Comment
Please, Sign In to add comment