Friday, April 18, 2014

Magic Square in Java

I have implemented magic square with simple code using Up-Left-Down logic.

I have used next and prev methods to get these up, left and down functions for re-usability.

And i have added logic to display the numbers as it various with starting number and the size of the magic square.

Here is the code and please leave your comments for your suggestions.


public class MagicSquare {
       private final int[][] square;
       private final int size;
       private final int start;
       private int row;
       private int col;

       public MagicSquare() {
              this(3, 1);
       }

       public MagicSquare(int size) {
              this(size, 1);
       }

       public MagicSquare(int size, int start) {
              if (size < 1 || size % 2 == 0 || start < 1) {
                     throw new RuntimeException("Invalid Params for Magic Box.");
              }
              this.size = size;
              this.start = start;
              this.square = new int[size][size];
              this.row = 0;
              this.col = (size - 1) / 2;
              this.solve();
       }

       private void solve() {
              int fill = start;
              while (fill < (size * size) + start) {
                     square[row][col] = fill;
                     fill = fill + 1;
                     next();
              }
       }

       public void next() {
              int nRow = prev(row);
              int nCol = next(col);
              if (square[nRow][nCol] == 0) {
                     row = nRow;
                     col = nCol;
              } else {
                     row = next(row);
              }
       }

       public int next(int num) {
              if (num == size - 1) {
                     return 0;
              }
              return num + 1;
       }

       public int prev(int num) {
              if (num == 0) {
                     return size - 1;
              }
              return num - 1;
       }

       public void display() {
              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", square[i][j]);
                     }
              }
       }

       public static void main(String[] args) {
              int size = 3;
              int start = 2;
              MagicSquare ms = new MagicSquare(size, start);
              ms.display();
       }
}

No comments:

Post a Comment