473,471 Members | 2,613 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Sudoku C

11,448 Recognized Expert MVP
Greetings,

welcome back to part three of the Sudoku article. This part describes the actual
Sudoku solver. The solver works quite simple: given a cell to be filled in,
try all possible values and solve the rest of the board. If all cells are filled
the Sudoku puzzle is solved.

The solver iterates over all cells, left to rigth, top to bottom. It receives
two parameters i and j which are the indexes of the cell to be filled in. The
cell could be filled in already (it was a given cell value) in which case the
solver has to find a next position. The first part of the solve method tries
to find an empty cell:
Expand|Select|Wrap|Line Numbers
  1. private boolean solve(int i, int j) {
  2.  
  3.     for(;;) {
  4.         if (j >= columns.length) {
  5.             j= 0;
  6.             i++;
  7.         }
  8.  
  9.         if (i >= rows.length) return true;
  10.  
  11.         if (board[i][j] > 0) j++;
  12.         else break;
  13.     }
  14.     ...
If you carefully inspect this piece of code you see that every row is checked,
column by column. When the last column has been checked a next row is checked
again until all cells are checked in which case the Sudoku puzzle is solved
and true is returned. Otherwise an empty cell has been found and the piece of
the code following this for loop is executed. The next piece of this method
recursively tries to solve the Sudoku puzzle:
Expand|Select|Wrap|Line Numbers
  1.     ...
  2.     for (int val= 0; val < squares.length; val++) {
  3.         if (possible(i, j, val)) 
  4.             if (!solve(i, j+1)) {
  5.                 reset(i, j);
  6.             }
  7.             else
  8.                 return true;
  9.     }
  10.  
  11.     return false;
  12. }
For the current cell all values 0 ... 8 are tried. If a value is feasible
it is filled in and an attempt is made to solve the rest of the Sudoku puzzle.
If the attempt fails the cell is reset and a next value is tried. If the
attempt was successful the method returns immediately because the entire
puzzle was solved. Otherwise the loop ends (none of the values were feasible
for that particular cell i,j) and the method returns false.

Note that this method is a private method. I did that on purpose because I
don't want other objects to supply the two index values. Here's a public
method that does it for them:
Expand|Select|Wrap|Line Numbers
  1. public boolean solve() {
  2.     return solve(0, 0);
  3. }
All we need now is a simple driver method that creates a Sudoku solver object,
opens a Reader, initializes the puzzle and fires up the solver. We'll implement
the driver functionality in the main() method for reasons of simplicity:
Expand|Select|Wrap|Line Numbers
  1. public static void main(String[] args) throws Exception {
  2.  
  3.     Sudoku s= new Sudoku();
  4.     FileReader fr= new FileReader(args[0]);
  5.  
  6.     if (s.read(new FileReader(args[0))) {
  7.         if (s.solve()) {
  8.             s.print(new OutputStreamWriter(System.out));
  9.         }
  10.         else
  11.             System.err.println("problem cannot be solved");
  12.     }
  13.     else
  14.         System.err.println("problem file cannot be read");
  15. }
Note that this is a very sloppy implementation, i.e. when something goes
seriously wrong, e.g. no file name was passed to the main method or the
actual reading failed, an Exception is simply passed on to the JVM which will
print an ugly stack trace. We even didn't bother to close the FileStream
properly: when the JVM exits the FileReader will be closed anyway.

I leave it up to your imagination and creativity to implement a proper,
industrial strength driver. The one above serves fine for demonstration
purposes in this article.

I created a file "/sudoku.txt" with the following content I found in an
old newspaper:
Expand|Select|Wrap|Line Numbers
  1. +-------+-------+-------+
  2. | 7 . . | . . . | 4 . . | 
  3. | . 2 . | . 7 . | . 8 . |
  4. | . . 3 | . . 8 | . . 9 |
  5. +-------+-------+-------+ 
  6. | . . . | 5 . . | 3 . . |
  7. | . 6 . | . 2 . | . 9 . |
  8. | . . 1 | . . 7 | . . 6 |
  9. +-------+-------+-------+ 
  10. | . . . | 3 . . | 9 . . |
  11. | . 3 . | . 4 . | . 6 . |
  12. | . . 9 | . . 1 | . . 5 |
  13. +-------+-------+-------+
Then I started the Sudoku class:
Expand|Select|Wrap|Line Numbers
  1. java -classpath . Sudoku /sudoku.txt
And this is what was printed almost immediately:
Expand|Select|Wrap|Line Numbers
  1. +-------+-------+-------+
  2. | 7 9 8 | 6 3 5 | 4 2 1 | 
  3. | 1 2 6 | 9 7 4 | 5 8 3 | 
  4. | 4 5 3 | 2 1 8 | 6 7 9 | 
  5. +-------+-------+-------+
  6. | 9 7 2 | 5 8 6 | 3 1 4 | 
  7. | 5 6 4 | 1 2 3 | 8 9 7 | 
  8. | 3 8 1 | 4 9 7 | 2 5 6 | 
  9. +-------+-------+-------+
  10. | 6 1 7 | 3 5 2 | 9 4 8 | 
  11. | 8 3 5 | 7 4 9 | 1 6 2 | 
  12. | 2 4 9 | 8 6 1 | 7 3 5 | 
  13. +-------+-------+-------+
I checked the next days' newpaper and indeed: both the newspaper as well as the
solver showed this same solution. Just for fun I changed the content of my
/sudoku.txt file:
Expand|Select|Wrap|Line Numbers
  1. +-------+-------+-------+
  2. | . . . | . . . | . . . | 
  3. | . . . | . . . | . . . |
  4. | . . . | . . . | . . . |
  5. +-------+-------+-------+ 
  6. | . . . | . . . | . . . |
  7. | . . . | . . . | . . . |
  8. | . . . | . . . | . . . |
  9. +-------+-------+-------+ 
  10. | . . . | . . . | . . . |
  11. | . . . | . . . | . . . |
  12. | . . . | . . . | . . . |
  13. +-------+-------+-------+
and fired up the solver again; this was the output:
Expand|Select|Wrap|Line Numbers
  1. +-------+-------+-------+
  2. | 1 2 3 | 4 5 6 | 7 8 9 | 
  3. | 4 5 6 | 7 8 9 | 1 2 3 | 
  4. | 7 8 9 | 1 2 3 | 4 5 6 | 
  5. +-------+-------+-------+
  6. | 2 1 4 | 3 6 5 | 8 9 7 | 
  7. | 3 6 5 | 8 9 7 | 2 1 4 | 
  8. | 8 9 7 | 2 1 4 | 3 6 5 | 
  9. +-------+-------+-------+
  10. | 5 3 1 | 6 4 2 | 9 7 8 | 
  11. | 6 4 2 | 9 7 8 | 5 3 1 | 
  12. | 9 7 8 | 5 3 1 | 6 4 2 | 
  13. +-------+-------+-------+
The output clearly shows that the solver works its way through the problem in
a strictly left to right, top to bottom manner: check the first row and the
first sub-square and see the regularity.

This is a naive solver but it works fine for the problems I tried. Some problems
are considered to be extremely difficult. Play with this solver a bit, feed it
some of those difficult problems and see how it runs.

The Sudoku class only needs a Reader and a Writer, i.e. it doesn't care how
these streams were created. You can even create a free Sudoku solver server
out of it if you feel like it: wrap a Reader around an InputStream created
by a socket. Do the same for the Writer and the socket's OutputStream.

This solver finds the 'first' solution given a problem. You might try and
alter the 'solve' method a bit so that it finds all solutions. It's up to you.

Until next week when a bit more serious matters will be discussed a bit.

kind regards,

Jos
May 12 '07 #1
1 6176
chellash
1 New Member
We classify difficulty levels as Easy, Medium and Hard. I had used Observer Pattern to solve easy ones . I hope your solution would solve all levels.
Dec 11 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: sub1ime_uk | last post by:
Thought I'd offer a method for solving all possible 9x9 sudoku puzzles in one go. It'll takes a bit of time to run however (and 9x9 seems to be about as big as is reasonably possible before...
5
by: Stewart Gordon | last post by:
I have a few Sudoku puzzles on my site. http://www.stewartsplace.org.uk/mindbenders/ But adding extra columns and rows to separate the 3x3 blocks seems a rather kludgy approach, and the result...
11
by: ago | last post by:
Inspired by some recent readings on LinuxJournal and an ASPN recipe, I decided to revamp my old python hack... The new code is a combination of (2) reduction methods and brute force and it is quite...
12
by: kalinga1234 | last post by:
hy guys i am having a problem with my sudoku program which i coded using c++.; currently in my program if a duplicate number exist in either row/column/block i would make the particualr square...
0
by: JosAH | last post by:
Greetings, a couple of years ago a large part of the world went totally mad. Not because of global climate changes, not because of terrible wars that were started in the Middle East, nor because...
6
by: blux | last post by:
I am working on a function to check the validity of a sudoku puzzle. It must check the 9x9 matrix to make sure it follows the rules and is a valid sudoku puzzle. this is what I have come up with...
21
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite...
3
by: deanchhsw | last post by:
Hello, I'm trying to build a program that solves sudokus and prints out the result on the screen. Here's the code for the class SudokuBoard. this will later be called in a class Sudoku. I'm a newbie,...
1
by: deanchhsw | last post by:
Part A (http://bytes.com/topic/java/insights/645821-sudoku) B (http://bytes.com/topic/java/insights/739704-sudoku-b) C (http://bytes.com/topic/java/insights/739703-sudoku-c) this question refers...
3
by: DannyB13 | last post by:
Hi, and thanks for possible help in advance. Here's my dilemma. I've been making a sudoku generator, and I'm now stuck on one part. I must be able to take a 'solution' and verify that it is correct,...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.