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);
      }

}

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();
       }
}

Sudoku in Java

I have tried to given the best solution finder for SUDOKU and even i have added some stuff to display the solution. So you can have a look on both logic and display functionality.

Here is the solution in java:

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MySudoku {   
       private final int[][] matrix;
       private final boolean solved;

       public MySudoku(int[][] matrix) {
              this.matrix = matrix;
              this.solved = solve(0, 0);
       }

       private boolean check(int row, int column, int value) {
              int boxRow = (row / 3) * 3;
              int boxColumn = (column / 3) * 3;

              for (int index = 0; index < 9; index++) {
                     if ((matrix[row][index] == value)// check the row
                                  || (matrix[index][column] == value) // check the column
                                  || (matrix[boxRow + (index % 3)][boxColumn + (index / 3)] == value)) {
                           // check the box
                           return false;
                     }
              }
              return true;
       }

       private boolean solve(int row, int column) {
              if (row == 9) {
                     row = 0;
                     column = column + 1;
                     if (column == 9) {
                           return true;
                     }
              }
              if (matrix[row][column] != 0) {// to skip the filled cells.
                     return solve(row + 1, column);
              }

              for (int value = 1; value <= 9; value++) {
                     if (check(row, column, value)) {
                           matrix[row][column] = value;
                           if (solve(row + 1, column)) {
                                  return true;
                           }

                     }
              }
              matrix[row][column] = 0; // this is playing import role to reset back.
              return false;
       }

       public void displaySolution() {
              if (solved) {
                     Runnable Runnable = new Runnable() {
                           public void run() {
                                  final JTextField[][] cells = new JTextField[9][9];
                                  final JPanel panel = new JPanel();
                                  final JFrame frame = new JFrame("Sudoku Board");
                                 
                                  for (int row = 0; row < 9; row++) {
                                         for (int col = 0; col < 9; col++) {
                                                cells[row][col] = new JTextField();
                                                cells[row][col].setText("  "
                                                              + String.valueOf(matrix[row][col]) + "  ");
                                                panel.add(cells[row][col]);
                                         }
                                  }
                                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                  frame.setLayout(new GridBagLayout());
                                  Insets insets = new Insets(0, 0, 0, 0);
                                  GridBagConstraints gbc = new GridBagConstraints(0, 0, 0, 0,
                                                1, 1, GridBagConstraints.CENTER,
                                                GridBagConstraints.BOTH, insets, 0, 0);
                                  frame.add(panel, gbc);
                                  frame.setSize(280, 280);
                                  frame.setVisible(true);
                           }
                     };
                     EventQueue.invokeLater(Runnable);
              } else {
                     System.out.println("No Solution Available.");
              }
       }
      
       public static void main(String[] args) {
              int[][] matrix = new int[][] { { 0, 8, 0, 4, 0, 2, 0, 6, 0 },
                           { 0, 3, 4, 0, 0, 0, 9, 1, 0 }, { 9, 6, 0, 0, 0, 0, 0, 8, 4 },
                           { 0, 0, 0, 2, 1, 6, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                           { 0, 0, 0, 3, 5, 7, 0, 0, 0 }, { 8, 4, 0, 0, 0, 0, 0, 7, 5 },
                           { 0, 2, 6, 0, 0, 0, 1, 3, 0 }, { 0, 9, 0, 7, 0, 1, 0, 4, 0 } };
              new MySudoku(matrix).displaySolution();
       }
}