Skip to content

Instantly share code, notes, and snippets.

@fulldecent

fulldecent/sudoku.pl

Last active Oct 8, 2015
Embed
What would you like to do?
Perl Sudoku solver
#!/usr/bin/perl
# usage: $0 00030050204050205040520370782340520508485019857294857049587
use integer;
@A = split //, <>;
sub R {
return if grep { # if this solution is invalid, bail
($_ / 9 == $i / 9 # find pairs of boxes to compare
|| $_ % 9 == $i % 9
|| $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3)
&& $_!=$i && $A[$i] && $A[$_]==$A[$i] } 0 .. 80;
print @A; # debug
$i++ while $A[$i]; # save this the child calls
my$x=$i;
die @A if $i>80; # out of bounds
R( $A[$i=$x] = $_ ) for 1..9; # recurse on each possible choice
$A[$x]=0;
# return $i=$x;
}
R
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment