Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //(c) A+ Computer Science
- //www.apluscompsci.com
- //Name -
- import java.util.Scanner;
- import static java.lang.System.*;
- public class MagicSquare1
- {
- private int[][] mat;
- //size the matrix and load in the numbers into the matrix
- //write all nested loop code here in the constructor
- public MagicSquare1(int size, int[] numbers)
- {
- mat = new int[size][size];
- int k = 0;
- for( int i = 0; i < size; i++)
- {
- for( int j = 0; j < size; j++)
- {
- mat[i][j] = numbers[k];
- k++;
- }
- }
- }
- public boolean isMagicSquare()
- {
- int x = sumRow(0);
- for(int i = 1; i < mat.length; i++)
- {
- if(sumRow(i)!=x)
- return false;
- }
- for(int i = 1; i < mat[0].length; i++)
- {
- if(sumCol(i)!=x)
- return false;
- }
- if(sumDownDiag()!=x)
- return false;
- if(sumUpDiag()!=x)
- return false;
- return true;
- }
- public int sumRow( int r )
- {
- int sum = 0;
- for( int v : mat[r] )
- {
- sum+= v;
- }
- return sum;
- }
- public int sumCol( int c )
- {
- int sum = 0;
- for( int i = 0; i < mat.length; i++ )
- {
- sum+= mat[i][c];
- }
- return sum;
- }
- public int sumDownDiag()
- {
- int sum = 0;
- for( int i = 0; i < mat.length; i++ )
- {
- sum+= mat[i][i];
- }
- return sum;
- }
- public int sumUpDiag()
- {
- int sum = 0;
- for( int i = 0; i < mat.length; i++ )
- {
- sum+= mat[mat.length-i-1][i];
- }
- return sum;
- }
- public String toString()
- {
- String output="";
- for( int[] row : mat )
- {
- for( int val : row)
- {
- output += val + " ";
- }
- output += "\n";
- }
- return output.trim();
- }
- public String magicOrNot()
- {
- if( isMagicSquare() )
- return "MAGIC SQUARE";
- else
- return "NOT A MAGIC SQUARE";
- }
- public static void main(String[] args){
- MagicSquare1 square = new MagicSquare1(3, new int[]{8, 1, 6, 3, 5, 7, 4, 9, 2});
- System.out.println( square + "\n" + square.magicOrNot() );
- square = new MagicSquare1(3, new int[]{6, 1, 8, 7, 5, 3, 2, 9, 4});
- System.out.println( square + "\n" + square.magicOrNot() );
- square = new MagicSquare1(3, new int[]{8, 3, 1, 3, 5, 7, 9, 4, 2});
- System.out.println( square + "\n" + square.magicOrNot() );
- square = new MagicSquare1(4, new int[]{7, 12, 1, 14, 2, 13, 8, 11, 16, 3, 10, 5, 9, 6, 15, 4});
- System.out.println( square + "\n" + square.magicOrNot() );
- square = new MagicSquare1(5, new int[]{17, 24, 1, 8, 15, 23, 5, 7, 14, 16, 4, 6, 13, 20, 22, 10, 12, 19, 21, 3, 11, 18, 25, 2, 9});
- System.out.println( square + "\n" + square.magicOrNot() );
- square = new MagicSquare1(5, new int[]{17, 24, 1, 8, 5, 23, 5, 7, 14, 6, 4, 6, 13, 20, 2, 10, 12, 19, 21, 3, 11, 18, 25, 2, 9});
- System.out.println( square + "\n" + square.magicOrNot() );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement