Write a program that will take a 3x3 matrix and test to see if it is a magic squ
ID: 3730363 • Letter: W
Question
Write a program that will take a 3x3 matrix and test to see if it is a magic square. A 3x3 matrix is “magic” if all of the following sums are the same: each row, each column, and both diagonals.
The following example is a magic square because everything adds up to the same number (2+7+6=15, 9+5+1=15, 4+3+8=15, 2+9+4=15, 7+5+3=15, 6+1+8=15, 2+5+8=15, and 4+5+6=15).
2
7
6
9
5
1
4
3
8
Use functions – don’t put everything in main
Use loops to calculate the sums – don’t hardcode the calculation. For example, you don’t want something like sum = matrix[0][0] + matrix[0][1] + matrix[0][2]. That is hard to update if we change the size of the array
2
7
6
9
5
1
4
3
8
Explanation / Answer
class MagicSquareTest{
public static boolean isMagicSquare(int[][] arr){
final int n=arr.length;
final int nSquare=n*n;
final int M=(n*n*(n*n+1)/2)/n;
int sumOfRow=0, sumOfColoumns=0, sumOfPrimaryDiagonal=0, sumOfSecondaryDiagonal=0;
boolean[] flag= new boolean[n*n];
for(int row=0; row<n; row++){
sumOfRow=0;
sumOfColoumns=0;
for(int col=0; col<n; col++){
if(arr[row][col]<1 || arr[row][col]>nSquare) return false;
if(flag[arr[row][col]-1]==true) return false;
flag[arr[row][col]-1]=true;
sumOfRow += arr[row][col];
sumOfColoumns += arr[col][row];
}
sumOfPrimaryDiagonal += arr[row][row];
sumOfSecondaryDiagonal += arr[row][n-row-1];
if(sumOfRow!=M || sumOfColoumns!=M) return false;
}
if(sumOfPrimaryDiagonal!=M || sumOfSecondaryDiagonal!=M) return false;
return true;
}
public static void main(String []args){
int[][] a ={{4,9,2},
{3,5,7},
{8,1,6}};
if(isMagicSquare(a)){
System.out.println("Given Matrix is a Magic Square Test");
}else{
System.out.println("Given Matrix is not a Magic Square Test");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.