/**
* Benis Munezero, Kelvin Acevedo, and Kenneth Mortiniera
* COSC 237 Sec 001
* Assignment 1, Task 2, Magic square.
*/
import java.util.*;
public class Assign1Task2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean startContinue;
do {
int n = getOddPositiveInt(sc, "Enter the size of the matrix (Postivie and odd): ");
int [][] square = generateSquare(n);
printMagicSquare(square);
startContinue = getChar(sc, "Continue (y/n): ");
}
while (startContinue);
}
//Method to get an odd positive integer for square size
public static int getOddPositiveInt(Scanner in, String prompt) {
System.out.print(prompt);
while (true) {
if(!in.hasNextInt()) {
in.next();
System.out.println("Error! Not a valid intenger.\nPlease input a valid intenger!");
}
else {
int num = in.nextInt();
if (num % 2 == 0 || num <= 0) {
System.out.println("Error! Invalid size! ");
}
else {
return num;
}
}
}
}
// Method to get char to start, coninue or end program
public static boolean getChar(Scanner in, String prompt) {
boolean isValid;
String s;
do {
System.out.print(prompt);
s = in.next();
isValid = (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("n"));
if (!isValid) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
} while (!isValid);
return s.equalsIgnoreCase("y");
}
// Method to generate odd sized square
public static int [][] generateSquare(int n) {
int[][] magicSquare = new int[n][n];
//Initialize position for 1
int row = n - 1;
int col = n / 2;
magicSquare[row][col] = 1;
// One by one put all values in magic square
for (int i = 2; i <= n * n; i++) {
if (magicSquare[(row + 1) % n][(col + 1) % n] == 0) {
row = (row + 1) % n;
col = (col + 1) % n;
}
else {
row = (row - 1 + n) % n;
}
magicSquare[row][col] = i;
}
return magicSquare;
}
// Method to print magic square
public static void printMagicSquare(int[][] magicSquare) {
int n = magicSquare.length;
System.out.println("The matrix with size = " + n
+ " is:");
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < n; j++) {
System.out.printf("%3d",magicSquare[i][j]);
}
System.out.println();
}
System.out.println("The " + n + "x" + n + " matrix adds up to " + n * (n * n + 1) / 2);
}
}