Friday, April 18, 2014

MagicSquarePlus.java

public class MagicSquarePlus {
      public void solve(int size, int start) {
            if (size < 1 || size % 2 == 0 || start < 1) {
                  throw new RuntimeException(
                              "Size must be add and Start must be positive.");
            }
            int[][] magic = new int[size][size];

            int row = size - 1;
            int col = size / 2;
            magic[row][col] = start;

            int last = size * size + start;
            for (int i = start + 1; i < last; i++) {
                  if (magic[(row + 1) % size][(col + 1) % size] == 0) {
                        row = (row + 1) % size;
                        col = (col + 1) % size;
                  } else {
                        row = (row - 1 + size) % size;
                  }
                  magic[row][col] = i;
            }
            display(magic, size, start);
      }

      private void display(int[][] magic, int size, int start) {
            int space = 2;

            int tmpSquare = size * size;
            while (tmpSquare > 0) {
                  tmpSquare = tmpSquare / 10;
                  space = space + 1;
            }
            int tmpStart = start;
            while (tmpStart > 0) {
                  tmpStart = tmpStart / 10;
                  space = space + 1;
            }
            for (int i = 0; i < size; i++) {
                  System.out.println();
                  for (int j = 0; j < size; j++) {
                        System.out.printf("%" + space + "d", magic[i][j]);
                  }
            }
      }

      public static void main(String[] args) {
            MagicSquarePlus ms = new MagicSquarePlus();
            ms.solve(3, 6);
      }

}

No comments:

Post a Comment