Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3
Solution
ANSWER:
public class MagixSquare {
public static boolean checkMagixSquare(int arr[][]) {
int count = 0;
int addRows = 0, addCols = 0, firstAdjecent = 0, secondAdjecent = 0;
for (int row = 0, skip = 2; row < 3; row++, skip--) {
addRows = 0;
addCols = 0;
firstAdjecent = firstAdjecent + arr[row][row]; // Adding adjacent
// values
for (int col = 0; col < 3; col++) {
addRows = addRows + arr[row][col]; // Adding each row
addCols = addCols + arr[col][row]; // Adding each column
int replace = skip;
if (replace == 0) {
secondAdjecent = secondAdjecent + arr[row][col]; // Adding
// adjacent
// values
}
replace--;
}
if (addRows == 15 && addCols == 15)
count++;
}
if (count == 3 && firstAdjecent == 15 && secondAdjecent == 15) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[][] = new int[3][3];
try {
System.out
.println(\"Run the program using command line arguments: \");
for (int row = 0, argCount = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
int val = Integer.valueOf(args[argCount++]);
if (val > 0 && val < 10)
arr[row][col] = val;
else {
System.out.println(\"Enter values between 0 to 9 only \");
break;
}
}
}
if (checkMagixSquare(arr)) {
System.out.println(\"Magix Square\");
} else {
System.out.println(\"Not Magix Square\");
}
} catch (Exception e) {
System.err.println(\"Error Message: \" + e.getMessage());
}
}
}
INPUT: Run the above program using command line argument and give values as follows:
4 9 2 3 5 7 8 1 6 respectively
OUTPUT: Magix Square

