Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MagicSquare {
- public static void main(String[] args) {
- // TODO Auto-generated method stub\
- int[][] matrix = {{2,7,6},{9,5,1}, {4, 3, 8} };
- boolean finale = isMagicSquare(matrix);
- if(finale == true){
- System.out.println("It is a Magic Square");
- }
- else {System.out.println("It is NOT a Magic Square");
- }
- }//end main
- public static boolean isMagicSquare(int[][] a) {
- boolean result1 = false, result2 = false;
- int[] sumRows = new int[a.length];
- int[] sumCols = new int[a.length];
- int sumDiag1 = 0, sumDiag2 = 0;
- //initialize sumRows and sumCols arrays with 0's
- for(int r=0; r < a.length; r++) {
- sumRows[r] = 0;
- sumCols[r] = 0;
- }//end for
- for(int r=0; r < a.length; r++) {
- for(int c=0; c < a.length; c++) {
- sumRows[r] += a[r][c];
- sumCols[c] += a[r][c];
- if(r == c){
- sumDiag1 += a[r][c];
- }//end if
- }//end for c
- }//end for r
- //loops for calculating sumDiag2
- for(int c=a.length-1; c >= 0; c--){
- for(int r=0; r < a.length; r++){
- if((r+c) == a.length-1) {
- sumDiag2 += a[c][r];
- }//end if
- }//end r
- }//end c
- if (sumDiag1 == sumDiag2) { result1 = true; }
- //Check if the sum of rows and columns are equal
- for(int r=0; r < a.length; r++) {
- if(sumRows[r] != sumCols[r]) {
- result2 = false;
- }//end if
- else {
- result2 = true;
- }
- }//end for
- //then if all the results are true, it is a magic square
- if(result1 && result2){
- return true;
- }
- else { //it is not a magic square
- return false;
- }
- }//end isMagicSquare()
- }//end class
Advertisement
Add Comment
Please, Sign In to add comment