This is a simple sudoku solver (if written unformatted, it's about 7x80-char lines of code). I'm a beginner in Perl, and this looked like a good first program, but of course there are surely many naiveties in the code. Any criticism/remark/comments welcome.
use strict; use warnings;my @r; sub r{my $l=shift;my%x=(); for(0..8){$x{int($l/9)*9+$_}="" ;$x{($l%9)+($_*9)}="";}my$k=int($l /27)*27+int( ($l%9)/3)*3; @x{$k..$k+2, $k+9..$k+11, $k+18..$k+20 }=("")x9; delete $x{$l}; return %x;}sub v{for(0..80){ next if($_[$_ ]eq".");return 0 if (join("", @_[@{$r[$_]}]) =~/$_[$_]/) } return 1}sub z{ my($p,@s)= (shift,@_); v( @s)||return 0; print"Cur: ", @s;for(;$s[$p ]ne".";$p++){ return print"end: ",@s if($p==81); }for(1..9){$s[$p]=$_;return 1 if (z($p+1,@s));}}for(0..80){my %r=r($_);$r[$_]=[keys %r]; };z(0,split(//,<>));
To use it, just give it the 81-chars string representing the board on stdin, eg
echo ".21.3.74.9.8...1 (snip) 3.9.65.1.42." | sudoku.pl
|
|---|