Dec 172006
 

This past week, I wrote a perl script to solve sudoku puzzles. The approach I took essentially works by brute force, but it works and the puzzle size is small. I might try to think of a better way to solve the puzzle. I intentionally did not look at other solutions so I could write my own.

The way you run the script is to type in something like perl -w sudoku.pl < puzzle where puzzle is the name of the file containing the puzzle. It should have 81 numbers from 0-9; 0 represents blank spaces. So this:
% cat puzzle2
0 6 0 0 5 0 0 2 0
0 0 0 3 0 0 0 9 0
7 0 0 6 0 0 0 1 0
0 0 6 0 3 0 4 0 0
0 0 4 0 7 0 1 0 0
0 0 5 0 9 0 8 0 0
0 4 0 0 0 1 0 0 6
0 3 0 0 0 8 0 0 0
0 2 0 0 4 0 0 5 0

gets turned into this:
% perl -w sudoku.pl < puzzle2
8 6 1 4 5 9 7 2 3
4 5 2 3 1 7 6 9 8
7 9 3 6 8 2 5 1 4
2 1 6 8 3 5 4 7 9
9 8 4 2 7 6 1 3 5
3 7 5 1 9 4 8 6 2
5 4 7 9 2 1 3 8 6
1 3 9 5 6 8 2 4 7
6 2 8 7 4 3 9 5 1

If there is more than one solution, only one solution is displayed. If there is no solution, you see an error message.

The Perl Sudoku solver can be downloaded from my site. Rename the file to sudoku.pl after downloading.

 Posted by at 4:16 pm

Leave a Reply