You are on page 1of 37

SUDOKU SOLVER

A Summer Training Report Submitted in partial fulfillment for the award of the Degree of

BACHELOR OF TECHNOLOGY
(with specialization in COMPUTER SCIENCE ENGINEERING) Submitted By:

AMBIKA SHARMA
(Roll No. - 208CS005)

Department of Computer Science & Engineering LES FILLES MODERN VIDYA NIKETAN INSTITUTE OF ENGINEERING & TECHNOLOGY, PALWAL (MAHARSHI DAYANAND UNIVERSITY, ROHTAK) SEPTEMBER 2011

SUDOKU SOLVER

Candidates Declaration
I hereby declare that the work which is being presented in the report,entitled SUDOKU SOLVER in partial fulfillment for the award of Degree of Bachelor of Technology in Department of Computer Science & Engineering with specialization in Computer Science & Engineering, submitted to the Department of Computer Science & Engineering, Les Filles Modern Vidya Niketan Institute of Engineering and Technology, Palwal( MAHARSHI DAYANAND UNIVERSITY,ROHTAK) is a record of my own investigations carried under DUCAT TRAINING INSTITUTE FOR SOFTWARES,SEC-16 FARIDABAD(HARYANA). I have not submitted the matter presented in this report anywhere for the any other Degree.

Ambika Sharma Computer Science & Engineering Roll No. - 208CS005 College Name - Les Filles MVN Institute of Engg. & Technology Counter Signed By

Name of HOD- Mr. Lalit Goyal Computer Science & Engineering College Name - Les Filles MVN Institute of Engg. & Technology

SUDOKU SOLVER

ACKNOWLEDGEMENT
I take this opportunity to thank all those who have helped me in completing the project successfully. I sincerely thank Mr. Lalit Goyal ( H.O.D. of the Institute ) of Les Filles Modern Vidya Niketan Institute of Engineering and Technology, Palwal for providing a platform to build this project and also like to show my gratitude for providing me with well trained faculty and giving all the required resources and a healthy environment for carrying out my project work. I am highly obliged to Mr. Vijay Kumar(Faculty of DUCAT Institute) for providing me continuous and invaluable guidance throughout the project. His kind and elderly advice always inspired me in putting my best efforts to develop an efficient project. Ambika Sharma (Roll No. 208CS005)

SUDOKU SOLVER

ABSTRACT
Our project is inspired from the orthodox Sudoku game in which the objective is to fill a 9x9 grid with digits so that each row, each column and each of the nine 3x3 sub-grids that compose the grid( also called boxes, regions ) contains all of the digits from 1to 9. You just have to provide a partially completely grid of puzzle setter Sudoku which will provide you with the solution which will be unique. The main purpose of the project is to provide user with the solution of the problem in very less time so that he is able to check with his solutions after carrying out mental activity onto the Sudoku game.

SUDOKU SOLVER

Table of Contents

Acknowledgement ... Abstract Table Of Contents 1 2 Introduction( With Company Profile)... Introduction to Project.. 2.1(a) Game Plan
2.1 (a) Overall Description

iii iv 5 6 7 8

3 4 5 6 7

Requirement Specification... Implementation. Compiling Source Code & Launching Game... Source Code.. Conclusion . References ..

12 18 20 23 36 37

SUDOKU SOLVER

INTRODUCTION
INSTITUTE PROFILE - DUCAT
Backed by a team of professionals who have successfully trained and placed students. DUCAT offers a wide spectrum of technical courses and application courses designed to suit every skill level, as well as the ability to consult directly with organizations to tailor made learning plans for any number of employees. Our products and services have a wide appeal and are applicable those in varied positions including network administrators, systems analysts, systems architects, test engineers, software developers, help desk staff, IT managers, senior executives, administrative assistants and business professionals.

SUDOKU SOLVER

INTRODUCTION TO PROJECT

SUDOKU SOLVER

GAME PLAN
In this game, there opens a window onto your computer screen. The window consists of a panel consisting of two buttons calculate and clear and 2-D array for solving the Sudoku game. calculate button is used to calculate the Sudoku and clear button to clear the cells of the matrix so that you can enter your own value into the Sudoku solver to the desired result. The user or the person will first have to execute the JAVA file and after entering the values into the Sudoku the desired result will be seen onto the window and also a text document will be created containing the values generated of Sudoku solver. Any repeat in the number in any row, any column or any of the nine 3x3 subgrids will result in a dead end of the program. So the input provided by the user should be unrepeated.

Start
When Sudoku is executed, a window is popped up as shown. It contains the default values as specified in the program. The Sudoku solver window cant be resized and upon clicking onto the calculate button the result will be displayed in the same window.

When the clear button will be clicked the following screenshot appear onto your system screen and you can enter the new values into the Sudoku solver to get the solution of the puzzle.

SUDOKU SOLVER

After clicking on the calculate button upon entering the values into the Sudoku solver you will be provided with the solution of the puzzle setter Sudoku which was containing partially occupied grids without any repeated numbers in any row, column or any of the nine sub-grids. It is shown below:

SUDOKU SOLVER

And if the entries in the Sudoku solver is repeated like in the following case then the Sudoku solver along with dos window will go into dead end because the solution to the partially completed puzzle cant be achieved as it contains the repeated values in the same column and you have to close the dos window to exit the Sudoku solver .Likewise if the puzzle contains any repeated values in any column or any of the nine 3x3 sub-grids the sudoku solver will result into dead end.

To quit the Sudoku solver you just have to right click onto the frame of the window or click on the red close button or close the dos window.

10

SUDOKU SOLVER

11

SUDOKU SOLVER

SOFTWARE REQUIREMENTS SPECIFICATION (SRS) FOR [SUDOKU SOLVER]


Requirement Specification Software Required
The project is implemented in Core Java as it is the Sudoku Solver which serves the main purpose to the user with the solution of the problem in very less time so that he is able to check with his solutions after carrying out mental activity onto the Sudoku game, hence the softwares required in the creation and execution of the project are j2sdk1.3 or JAVA DEVELOPMENT KIT 1.05 .As we know JAVA is a platform independent language so this software runs with JRE environment on any desired platform i.e. windows 9x, XP, or 2000 operating system.

Hardware Required:
As the project does not involve any database, its hardware requirements are minimal. Any System with Pentium P2 or above processor, 32MB RAM, 1GB Hard Disk, a LAN Card, and a CDROM is sufficient. Its network based software so computers connected with any kind of mode (wireless, LAN connected etc) will suit its requirements. . . . It can also be run on a single machine for its demo use. Best suited in laboratory where we can run its server on any machine and many clients can use it simultaneously.

12

SUDOKU SOLVER

ABOUT THE LANGUAGE JAVA

13

SUDOKU SOLVER

Software Analysis Report: JDK 1.5


About Java: Features
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM.

Simple
There are various features that make the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and de-allocation system.

Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.

Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed. Encapsulation: It is the mechanism of combining the information and providing the abstraction. Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods. Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.

As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java, it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.

Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust. 14

SUDOKU SOLVER

Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.

Portable
The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features make the java as a portable language.

Dynamic
While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.

Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The byte code Verifier checks the classes after loading.

Performance
Java uses native code usage, and lightweight process called threads. In the beginning interpretation of byte code resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance.

Multithreaded
Java is also a multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer. Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.

15

SUDOKU SOLVER

Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code. The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program. The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent. Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.

Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems.Not only to computer systems but to a wide variety of hardware architecture and operating system architectures as well. The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language.

16

SUDOKU SOLVER

ABOUT : JDK
The Java Development Kit (JDK) is a Sun Microsystems product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java SDK. On 17 November 2006, Sun announced that it would be released under the GNU General Public License (GPL), thus making it free software. This happened in large part on 8 May 2007[1] and the source code was contributed to the OpenJDK. The primary components of the JDK are a selection of programming tools, including:

java The loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, is no longer provided with Sun JDK. javac The compiler, which converts source code into Java bytecode jar The archiver, which packages related class libraries into a single JAR file. This tool also helps manage JAR files. javadoc The documentation generator, which automatically generates documentation from source code comments jdb The debugger javap The class file disassembler appletviewer This tool can be used to run and debug Java applets without a web browser. javah The C header and stub generator, used to write native methods extcheck This utility can detect JAR-file conflicts. apt The annotation processing tool jhat (Experimental) Java heap analysis tool jstack (Experimental) This utility prints Java stack traces of Java threads. jstat (Experimental) Java Virtual Machine statistics monitoring tool jstatd (Experimental) jstat daemon jinfo (Experimental) This utility gets configuration information from a running Java process or crash dump. jmap (Experimental) This utility outputs the memory map for Java and can print shared object memory maps or heap memory details of a given process or core dump. idlj The IDL-to-Java compiler. This utility generates Java bindings from a given IDL file. policy tool The policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources VisualVM visual tool integrating several command line JDK tools and lightweight performance and memory profiling capabilities

The JDK also comes with a complete Java Runtime Environment, usually called a private runtime. It consists of a Java Virtual Machine and all of the class libraries that will be present in the production environment, as well as additional libraries only useful to developers, such as the internationalization libraries and the IDL libraries. Also included are a wide selection of example programs demonstrating the use of almost all portions of the Java API.

17

SUDOKU SOLVER

implementation
In the program, we have used the following four java packages 1. java.util.Random has been used to generate random numbers through which objects of different colors are produced randomly. 2. javax.swing.* has been used for JFrame and JComponent. 3. java.awt.* has been used for Dimension, Image, Toolkit, Graphics, Container, Color and Graphics2D. 4. java.awt.event.* has been used for ActionListener, ActionEvent, KeyAdapter and KeyEvent. 5. java. text.* has been used to formats, searches and manipulates text. 6. Java.io.* has been used for the data output through OutputStream. 7. javax.swing.table.DefaultTableModel has been used for the generation of table on the basis of the default model specified.

Classes
1. Class sudoku is created by extending JFrame . It produces the window for the Sudoku solver applet. It also acts as the main class i.e. main function is defined in this class. Class contains a constructor which contains the panel, buttons for the calculate and clear, and init method . .Functions of class sudoku

1. Init() ---- to fill the matrix of Sudoku with the initial values .Every time you run the Sudoku you will be seeing these values which can be cleared and after entering new values you will be getting the solution of the problem. 2. Row() ---a vector is created for this function to create a dynamic array and legacy method addElement(E element) of vector is used to enter the data into a particular row. 3. Column() ---a vector is created for this function to create a dynamic array and legacy method addElement(E element) of vector is used to enter the data into a particular column. 4. Mat3x3() ---- a vector is created for this function to create a dynamic 2-D array and legacy method addElement(E element) of vector is used to enter the data into a particular cell of 2-D array. 5. Sudoku() ---default constructor of class Sudoku. 6. actionPerformed() ---- to capture events generated by different buttons. 7. GeneratePossibleElements() ---- to generate the possible values that can into a particular cell of a2-D array. HashTable is used which is used to the key, value pairs into the hash table object is used as a key and object is linked to data value. 18

SUDOKU SOLVER

8. Solve() ---in this first a backup data is created. It finds the cell with minimum options to be filled and if there is single option then it is filled with that data value ,if more than one options then it checked for all those values and if still the 2-D array has zero values then this process is repeated till there arent any zero values in any cells.

9. findCellWithMinimumOptions() ---- it uses the hash table and finds the cell with minimum number of options to get filled. 10. WriteIntoFile() ---it is used to write the output into the file using OutputStream. 11. Reset() ---- it is used to reset the Sudoku solver. 12. find_unique_elements() ---it finds the elements to be filled in a particular cell. 13. findmatstartpoint() ---- it finds the starting left most cell of 3x3 matrix. 14. inc() ---- this function finds the next zero or element after a particular cell specified in the parameters of this function. 15. print() ---- this function is used to print the output on the completion of the problem. 16. no_of_positions_in_3x3_matrix() ---- finds the total no of positions in 3x3 matrix where a particular data value can be filled and returns the total no of positions. 17. canbfilled() ---- this function finds whether a particular cell can be filled with a data value specified in the parameters of the function. This function returns a Boolean value true if the can be occupied with that value otherwise it returns false. 18. FillOnlyPossibleElements() ---this function finds the candidate positions where only one value can be entered. 19. FillUniquePositionsIn3x3Matrix() ---this function will find the elements that can be filled only at particular position and fills it there and increment the nonzero values. 20. FillUniquePositionInRows() ---this function will find the particular row where the data value can be entered and fills it incrementing the nonzero values. 21. FillUniquePositionInCols() ---this function will find the particular column where the data value can be entered and fills it incrementing the nonzero values. 22. CountNonZero() ---this function will find total number of nonzero values present.

19

SUDOKU SOLVER

COmPILING THE SOURCE CODE AND LAUNCHING THE GAME


1. The source code file is sudoku.java which can be saved onto your systems. 2. JDK must be installed onto the system where you want to compile and run this game. 3. Open command prompt and change the current working directory to the directory where the source code file exists. 4. Then enter the command javac sudoku.java. This command will compile the code and create class files at the same place where the java file is present . 5. To run the Sudoku enter the command java sudoku. A window opens to launch the game. Enter the minimum number of values required to solve the problem and you will get the output on the dos window. Also a text document will be generated having values that will be present in the Sudoku after it is calculated. Screen shots for loading the Sudoku solver: Type cmd in the run ----

20

SUDOKU SOLVER

POSITION 1

Then go to desktop or other place where you have saved the java file and compile the file by he command javac sudoku.java

POSITION 2

21

SUDOKU SOLVER

POSITION 3 Then execute the Sudoku solver by writing the command java sudoku and following screen occurs where you can enter the values after clearing the contents of the Sudoku solver and clic onto the calculate button to get the solution of the partially completed puzzle maintain the constraints applied to it.

22

SUDOKU SOLVER

After the solution is achieved the dos window containing the following scenario:

SOURCE CODE
Import Import import import import import import java.awt.*; java.awt.event.*; java.text.*; java.util.*; java.io.*; javax.swing.*; javax.swing.table.DefaultTableModel;

/**************************************************************************/ public class sudoku extends JFrame implements ActionListener { JTable table=null; static Object data[][]=new Object[9][9]; Object cols[]=new Object[9]; int NumOfTabs = -1; int nonzero=0,nonzero1=0;

23

SUDOKU SOLVER

Hashtable<Integer,Set<Integer>> mp = new Hashtable<Integer,Set<Integer>>(); DefaultTableModel model=null; static Vector<Integer> test=new Vector<Integer>(9); static { for(int i=1;i<=9;i++) test.addElement(i); } /**********************************************************************/ sudoku(String s) { super(s); init(); model=new DefaultTableModel(data,cols); table=new JTable(model); table.setAutoCreateColumnsFromModel(true); JButton calculate=new JButton("Calculate"); JButton clear=new JButton("Clear"); calculate.addActionListener(this); clear.addActionListener(this); JPanel lp = new JPanel(); setResizable(false); lp.setLayout(new BorderLayout()); lp.add(table,BorderLayout.CENTER); lp.add(calculate,BorderLayout.NORTH); lp.add(clear,BorderLayout.SOUTH); getContentPane().add(lp); } /**********************************************************************/ public Vector<Integer> row(int n) { Vector<Integer> r=new Vector<Integer>(9); for(int i=0;i<=8;i++) try { r.addElement(Integer.parseInt(data[n][i].toString())); }catch(NumberFormatException e) { r.addElement(0); } return r; } /**********************************************************************/ public Vector<Integer> column(int n)

24

SUDOKU SOLVER

{ Vector<Integer> c=new Vector<Integer>(9); for(int j=0;j<=8;j++) try { c.addElement(Integer.parseInt(data[j][n].toString()) ) } catch(NumberFormatException e) { c.addElement(0); } return c; } /**********************************************************************/ public Vector<Integer> mat3x3(int x, int y) { Vector<Integer> mat3x3=new Vector<Integer>(9); for(int i=x;i<=x+2;i++) for(int j=y;j<=y+2;j++) try { mat3x3.addElement(Integer.parseInt(data[i][j].toString())); } catch(NumberFormatException e) { mat3x3.addElement(0); } return mat3x3; } /**********************************************************************/ void init() { for(int i=0;i<9;i++) for(int j=0;j<9;j++) data[i][j]=""; data[0][1]=4; data[0][4]=9; data[1][1]=9; data[1][4]=7; data[1][5]=2; data[2][2]=7; data[2][7]=2; data[3][0]=5; data[3][3]=3; data[3][6]=8; data[4][0]=3; data[4][8]=1; data[5][2]=6; data[5][5]=8; data[5][8]=3; data[6][1]=8;

25

SUDOKU SOLVER

data[6][6]=6; data[7][3]=6; data[7][4]=1; data[7][7]=9; data[8][4]=2; data[8][7]=4; } /**********************************************************************/ sudoku() { } /**********************************************************************/ public void actionPerformed(ActionEvent arg0) { nonzero=0; String str=(String)arg0.getActionCommand(); if(str.equalsIgnoreCase("Calculate")) { Date date = new Date(); System.out.print("\nTime = " + date); for(int i=0;i<9;i++) for(int j=0;j<9;j++) { try { data[i][j]=table.getValueAt(i,j); if(data[i][j].equals("")) data[i][j]=0; } catch(Exception e) { data[i][j]=0; } } solve(); countNonZero(); //Back Luck !! No solution if(nonzero<81) { System.out.print("\nUnable to find a solution " + nonzero); print(); } date = new Date(); DateFormat df; df=DateFormat.getDateInstance(DateFormat.LONG, Locale.UK); try { WriteIntoFile(df.format(date) + ".txt",table);

26

SUDOKU SOLVER

} catch(IOException ex) { System.out.println("An IO Exception occured"); } date = new Date(); System.out.print("\nTime = " + date); } //Now if the source is clear then, clear all the boxes if(str.equalsIgnoreCase("Clear")) { for(int i=0;i<9;i++) for(int j=0;j<9;j++) { data[i][j]=""; model.setValueAt(data[i][j],i,j); nonzero=0; } table.repaint(); } } /**********************************************************************/ public int GeneratePossibleValues(Hashtable<Integer,Set<Integer>> mp) { mp.clear(); for(int i=0;i<9;i++) for(int j=0;j<9;j++) if(data[i][j].equals(0) ) { Set<Integer> val = new HashSet<Integer>(); mp.put(i*10+j,val); } for(int i =0; i<=8;i++) for(int j=0;j<=8;j++) if(data[i][j].equals(0) ) { for(int k=1;k<=9;k++) if(canbfilled(k,i,j)) { Set<Integer> oldValue = new HashSet<Integer>(); oldValue = (Set<Integer>)mp.get(i*10+j); oldValue.add(k); mp.put(i*10+j,oldValue); } if(((Set)mp.get(i*10+j)).size()==0) return -1; } return 0; } /**********************************************************************/

27

SUDOKU SOLVER

public void solve() { Object tempdata[][] = new Object[9][9]; //Needs to take the backup... for(int i=0;i<9;i++) for(int j=0;j<9;j++) { tempdata[i][j]=data[i][j]; } //Fill Elements that can be uniquely identified. FillUnique(); if(nonzero>=81) return; //After calling Fillunique, GeneratePossibleValues, there may be some situation like dead end. //GeneratePossibleValues returns 0 on success, means, everycell has atleast one option. if(GeneratePossibleValues(mp)!=0) return; //This will give -1 when we reach dead end..... int cell = findCellWithMinimumOptions(mp); if(cell==-1) { //if we reach dead end then revert back to original data and return i.e. backtrack... for(int i=0;i<9;i++) for(int j=0;j<9;j++) { data[i][j]=tempdata[i][j]; } return; } //flow reaches here, means, there exists a cell that has 2 or more options. Set<Integer> possibleValues = (Set<Integer>)mp.get(cell); Iterator<Integer> iter = possibleValues.iterator(); int row = cell/10; int col = cell%10; //For each option we need to repeat the process.... while(iter.hasNext()) { int value=-1; value = (Integer)iter.next(); data[row][col]=value; System.out.print("."); solve(); countNonZero(); if(nonzero>=81) return; //Not successful, restore original data and try with the next option. for(int i=0;i<9;i++) for(int j=0;j<9;j++) { data[i][j]=tempdata[i][j]; } } } /**********************************************************************/

28

SUDOKU SOLVER

public static int findCellWithMinimumOptions(Hashtable<Integer, Set<Integer>> m) { int returnVal=9; int returnKey = -1; Set<Integer> keySet = m.keySet(); Iterator<Integer> iter = keySet.iterator(); while(iter.hasNext()) { int key = (Integer)iter.next(); int size = -1; try { size = ((Set<Integer>)m.get(key)).size(); } catch(Exception e) { System.out.print("\n\nException caught : " + e +"\n"); } if(size==0) return -1; if(returnVal>size && size>=2) { returnVal = size; returnKey = key; } } return returnKey; } /**********************************************************************/ public void FillUnique() { countNonZero(); nonzero1=nonzero; while(true) { FillOnlyPossibleElements(); FillUniquePositionsIn3x3(); FillUniquePositionsInRows(); FillUniquePositionsInCols(); //this condition is true when no further progress can be made. //countNonZero(); if(nonzero==nonzero1) break;//Further progress is not possible using unique elements else nonzero1=nonzero;//Further progress is possible. if(nonzero>=81) { System.out.println("\nSolution achieved"); for(int i=0;i<9;i++) for(int j=0;j<9;j++) model.setValueAt(data[i][j],i,j); table.repaint();

29

SUDOKU SOLVER

//JOptionPane.showMessageDialog(new JPanel(), "Solution achieved"); return; } } } /**********************************************************************/ public static void main(String[] args) { sudoku frame=new sudoku("Made by : Yogesh Gandhi"); frame.setSize(300,230); frame.setVisible(true); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); } /**********************************************************************/ public void WriteIntoFile(String filename, JTable tb) throws IOException { OutputStream f1 = new FileOutputStream(filename); String output=""; for(int i =0 ;i<9; i++) { for(int j =0 ; j< 9; j++) { output = output + data[i][j].toString()+(j%3==2 ? "\t" : " " ); } output = output + (i%3==2 ? "\n\n" : "\n"); } byte buf[]=output.getBytes(); f1.write(buf); f1.close(); } public void reset() { test.removeAllElements(); for(int i=1;i<=9;i++) test.addElement(i); } /**********************************************************************/ int find_unique_elements(int i,int j) {

30

SUDOKU SOLVER

int si[]=new int[1];//Actually these are variables I need to pass by int sj[]=new int[1];//reference, that is why they are created as arrays reset();//resets the test Vector //This function finds the top left point coordinates //of 3 X 3 matrix in which the point resides findmatstartpoint(si,sj,i,j); for(int a=1;a<=9;a++) //This loop removes the elements in //row no. i and column no. j and in 3x3 matrix from the test array { if(row(i).contains(a) || column(j).contains(a) || mat3x3(si[0],sj[0]).contains(a)) { test.removeElement(a); } } return(test.size()); } /**********************************************************************/ void findmatstartpoint(int s1[], int s2[],int i,int j) { s1[0] = (i/3)*3; //getting the nearest multiple of 3 <=i s2[0] = (j/3)*3; //getting the nearest muliple of 3 <=j } /**********************************************************************/ /*int findmin_in_test() { //This function will return the first nonzero element if available in test if(test.size()==1) return test.firstElement(); else return 0; }*/ /**********************************************************************/ void inc(int i[],int j[]) { //This function will find the next zero or "" element after (i,j) do { j[0]++; if(j[0]==9) { j[0]=0; i[0]++; } if(i[0]==9) return; }while(data[i[0]][j[0]].equals(0)==false);//data[i[0]][j[0]].equals(" ")==false && );

31

SUDOKU SOLVER

} /**********************************************************************/ void print() { int i,j; System.out.print("\n==================================================\n"); for(i=0;i<=8;i++) { if(i%3==0 && i!=0) System.out.println(); for(j=0;j<=8;j++) try { if(j%3==2) System.out.print(data[i][j]+"\t"); else System.out.print(data[i][j]+" "); } catch(Exception e) { if(j%3==2) System.out.print("\t"); else System.out.print(" "); } System.out.println(); } countNonZero(); System.out.print("\n\n"); System.out.print("Nonzero items = " + nonzero); System.out.print("\n==================================================\n"); } /**********************************************************************/ int no_of_positions_in_3x3_matrix(int a,int si,int sj) { int i=0,j=0,nopos=0; int ii=0,jj=0; for(i=si;i<=si+2;i++) for(j=sj;j<=sj+2;j++) if(canbfilled(a,i,j)) { ii=i; jj=j;//Store the last possible position of a nopos++; if(nopos>=2) return nopos;

32

SUDOKU SOLVER

} if(nopos==1) data[ii][jj]=a; return nopos; } /**********************************************************************/ boolean canbfilled(int a,int x,int y) { int si[]=new int[1]; int sj[]=new int[1]; if(data[x][y].equals(0)==false)// && data[x][y].equals(" ")==false) return false; findmatstartpoint(si,sj,x,y); if(row(x).contains(a) || column(y).contains(a) || mat3x3(si[0],sj[0]).contains(a)) return false; return true; } /**********************************************************************/ /* This function finds the candidate positions, where only one number can be filled*/ /* for e.g. at position (2,3) only 1 can be filled.*/ /* So, it will fill 1 at position 2,3.*/ void FillOnlyPossibleElements() { int i[]={0}; int j[]={-1}; while(true) { inc(i,j);//here i and j gets changed, that is why created as arrays. if(8<i[0]) break; if(find_unique_elements(i[0],j[0])==1) { //find nonzero element in test and assign it to data data[i[0]][j[0]]=test.firstElement();//findmin_in_test(); i[0]=0; j[0]=-1;//resets the value of i and j nonzero++; reset(); } } } /**********************************************************************/

33

SUDOKU SOLVER

/*This function will find the elements that can be filled only at some unique position in 3x3 matrix and fills it there and also increm ents nonzero static variable.*/ void FillUniquePositionsIn3x3() { int i,j,k; for(i=0;i<=6;i+=3) for(j=0;j<=6;j+=3) { for(k=1;k<=9;k++) if(no_of_positions_in_3x3_matrix(k,i,j)==1) { nonzero++; } } } /**********************************************************************/ void FillUniquePositionsInRows() { int i=0,j=0,k=0,nopos=0; int ii=0,jj=0; for(k=1;k<=9;k++) { for(i=0;i<=8;i++) { nopos=0; for(j=0;j<=8;j++) if(canbfilled(k,i,j)) { ii=i;jj=j; nopos++; } if(nopos==1) { data[ii][jj]=k; nonzero++; } } } } /**********************************************************************/ void FillUniquePositionsInCols() { int i=0,j=0,k=0,nopos=0; int ii=0,jj=0; for(k=1;k<=9;k++) {

34

SUDOKU SOLVER

for(j=0;j<=8;j++) { nopos=0; for(i=0;i<=8;i++) if(canbfilled(k,i,j)) { ii=i;jj=j; nopos++; } if(nopos==1) { data[ii][jj]=k; nonzero++; } } } } /***********************************************************************/ public void countNonZero() { nonzero=0; for(int i =0;i<9;i++) { for(int j=0;j<9;j++) { try { if(data[i][j].equals(0)==false && data[i][j].equals("")==false) nonzero++; } catch(Exception e) {} } } }//ends countNonZero /***********************************************************************/ }

35

SUDOKU SOLVER

CONCLUSIONS
Simple Sudoku is an excellent Sudoku game. This program is worthy of your consideration if this game provides the features you desire. If there is any drawback to this program, it is that it may take the fun out of solving Sudoku if you rely on its solving tools too much. Hunting for single candidates becomes a snap. Are you new to Sudoku? This program is an excellent teaching tool. It will help you solve difficult Sudoku puzzles using advanced techniques. Best for all users!!! These are the facts, you decide!!

36

SUDOKU SOLVER

REFERENCES
S.NO
1 2 3

TITLE
Java Complete Reference Pearson Core and Advance Java Volume 1 & 2

AUTHOR
Herbert Schildt Prentice Hall,New Jersey 2004 Cay S. Horstmann & Gary Cornell

37

You might also like