
// MagicSquare.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* A magic square of order n is an arrangement of distinct n^2
   integers,in a square, such that the n numbers in all
   rows, all columns, and both diagonals sum to the same constant. 

   https://en.wikipedia.org/wiki/Magic_square

   The code here only generates odd magic squares, using the 
   integers from 1 to n^2.

   Coding:
     odd: https://www.geeksforgeeks.org/magic-square/
    even: https://www.geeksforgeeks.org/magic-square-even-order/

   Usage:
     > compile MagicSquare.java
     > run MagicSquare <n>
   e.g.
     > run MagicSquare 3
     > run MagicSquare 5
*/


import java.util.*;


public class MagicSquare
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run MagicSquare <n>");
      return;
    }
    int n = Math.abs(Nut.parseInt(args[0]));
    if (n % 2 == 0) {
      System.out.println("Size must be odd; using 3");
      n = 3;
    }
    else 
      System.out.println("Size: " + n);

    // build the square
    int[][] magic = new int[n][n];
    int row = n / 2;
    int col = n - 1;
    magic[row][col] = 1;

    for (int i = 2; i <= n * n; i++) {
      if (magic[(row - 1 + n) % n][(col + 1) % n] == 0) {
        row = (row - 1 + n) % n;
        col = (col + 1) % n;
      }
      else
        col = (col - 1 + n) % n;
      magic[row][col] = i;
    }

    // print the square
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++)
        System.out.printf(" %3d ", magic[i][j]);
      System.out.println();
    }
  } /* main */


}  // end of MagicSquare class
