Sudoku solver
There are probably tons of these already available, but here is a quick sudoku solver (in Perl):
#! /usr/bin/perl
# Example:
#
# echo $' 2 \n 1 9 4 \n 2 1 5 9\n3 6 \n 68 41 5\n 427 8 \n 51 \n 7 3 \n79 5 '| perl sudoku-solve.pl
#
use strict;
use warnings;
my $s = read_sudoku();
my $res= solve($s);
if($res) {
print_sudoku($res);
print "Got it!\n";
} else {
print "Failed :-(\n";
}
exit 0;
sub solve {
my ($s)= @_;
my $res= try_solve($s);
return $s if $res eq 'SOLVED';
return undef if $res eq 'FAIL';
# Make a guess, backtracking if we were wrong.
# Try to find some field where there are only two possibilities.
my ($a, $b);
OUTER:
for my $i (0..8) {
INNER:
for my $j (0..8) {
next INNER if keys(%{$s->[$i][$j]}) == 1;
if(keys(%{$s->[$i][$j]}) == 2) {
($a,$b)= ($i,$j);
last OUTER;
} elsif(!defined($a)) {
($a,$b)= ($i,$j);
} …[Read more]