Skip to content

Instantly share code, notes, and snippets.

@fulldecent
Last active October 8, 2015 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fulldecent/3398930 to your computer and use it in GitHub Desktop.
Save fulldecent/3398930 to your computer and use it in GitHub Desktop.
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