In: Computer Science
The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in Figure 8-23. The Lo Shu Magic Square has the following properties:
l The grid contains the numbers 1 through 9 exactly.
l The sum of each row, each column, and each diagonal all add up to the same number. This is shown in Figure 8-24.
In a program, you can simulate a magic square using a two-dimensional array. Design a program that initializes a two-dimensional array with values entered by the user. The program should determine whether the array is a Lo Shu Magic Square.
Copyable Code:
MagicSquare.java:
public class MagicSquare
{
//function definition for check magic square
public static boolean checkMagicSquare(int[][] arr)
{
//declare the variable r for row, c for column
//declare the variable for sum
int sum=0,s, r, c,i;
for (c = 0; c<3; c++)
//assign the sum is 15 which is in two dimension array
sum += arr[0][c];
//check two rows
s = 0;
for (r = 1; r < 3; r++)
{
s = 0;
for (c = 0; c< 3; c++)
s += arr[r][c];
if (s != sum)
return false;
}
//validate columns
for (c = 0; c< 3; c++)
{
s = 0;
for (r = 0; r < 3; r++)
{
s += arr[r][c];
}
if (s != sum)
return false;
}
//validate diagonal 1
s =0;
for (r = 0; r < 3; r++)
{
s += arr[r][r];
}
if (s != sum)
return false;
//validate diagonal 2
s =0;
for (r = 0; r < 3; r++)
{
s += arr[r][2 - r];
}
if (s != sum)
return false;
//check that the numbers 1 to 9 existing
//assign the variable for selected
boolean[] selected = new boolean[9];
for (i=0; i < 9; i++)
{
selected[i] = false;
}
//check every number
for (c = 0; c< 3; c++)
{
for (r = 0; r < 3; r++)
{
int num = arr[r][c];
if (selected[num-1])
return false;
selected[num-1] = true;
}
}
//here check the every values in appears are true but
// since there are 9 positions in both selected and arr[][]
return true;
}
public static void main (String[] args)
{
int[][] sampleArray1 = {{4,9,2},{3,5,7},{8,1,6}};
System.out.println("Sample array 1 Lo Shu Magic Square: "+MagicSquare.checkMagicSquare(sampleArray1));
int[][] sampleArray2 = {{4,9,2},{3,1,5},{8,7,6}};
System.out.println("Sample array 2 Lo Shu Magic Square: "+MagicSquare.checkMagicSquare(sampleArray2));
}
}