Slightly silly perhaps but I thought it would be fun to write a piece of code to solve these sudoku puzzles that keep popping up. As that appeared to be trivial I decided to see if it could be done in four lines or less. Here it is:
$a=8;$G{int(++$a/9).$a%9+1}=$_ for split//,<>;@A=1..9;sub c{int(($_[0]-1
)/3)*3}sub G{for$y(@A){for$x(@A){$p=$t=$G{my$c=$y.$x}&&next;$t.=$G{$_.$x
}.$G{$y.$_}for@A;for$f(1..3){$t.=$G{c($y)+$f.c($x)+$_}for 1..3}G($G{$c}=
$_)&&return for grep$t!~m/$_/,@A;return$G{$c}=0}}die map{$G{$_}}9..99}G
Update – there is also an explanation of this code and a three line version.
It is slightly arcane in it’s usage but what do you expect from four lines of Perl? The best way to run it is to save it to a file (eg sudoku.pl). You need to feed it the start grid as well. This is one long line with the top row first, the second row next and so on. Use zeros for the blanks. Do not separate the rows with a space, just push them all together.
For example the following puzzle was given in the Economist (21 May 2005) on page 75:
. . . . 1 . . . . 3 . 1 4 . . 8 6 . 9 . . 5 . . 2 . . 7 . . 1 6 . . . . . 2 . 8 . 5 . 1 . (dots are used for the blanks) . . . . 9 7 . . 4 . . 3 . . 4 . . 6 . 4 8 . . 6 9 . 7 . . . . 8 . . . .
This would give you the following line for input:
000010000301400860900500200700160000020805010000097004003004006048006907000080000
If you saved the input in a file called input.txt you could then run the solver like this:
perl sudoku.pl < input.txt
The output is the same format as the input – that is to say all the rows on one line.
It will only work for 9×9 grids containing numbers 1 to 9. Hope you enjoy it.
2005/05/11 – scrpbk.com for all your scrapping needs
Just a quick note to let all know that I have just launched a new website scrpbk.com that lets you organize small bits of information and let the world see them.
You take bits of information (scraps) and organize them into groups (holders). You can move all of these around and tweak them as you like. All of this information is then visible to anyone on the web.
There is much more to come soon though, such as private holders, arranging holders over several pages and ‘social things’. If you have any idea please let me know.
People are already starting to sign up so hurry. Once your username is taken it is taken.
Impressive code; thanks for share it.