Created
June 14, 2010 15:45
-
-
Save patrickas/437866 to your computer and use it in GitHub Desktop.
slow ugly naive perl6 sudoku solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
my $SIZE = 9; | |
my $FOUND_NEW_STUFF = True; | |
multi sub eigenstates (Int $quantum_state) { $quantum_state } | |
multi sub eigenstates (Junction $quantum_state) { #return $quantum_state.eigenstates() ; #I wish | |
my @possibilities ; | |
for (1..$SIZE) { #Our universe is 1..9 :-) | |
@possibilities.push($_) if $_ ~~ $quantum_state; | |
} | |
if (@possibilities == 1) { | |
$FOUND_NEW_STUFF = True; | |
return @possibilities[0] ; | |
} | |
return any(|@possibilities); | |
} | |
sub cols(@p , $row,$col) {return map {@p[$row][$_].Int} , ^$SIZE } | |
sub rows(@p , $row,$col) {return map {@p[$_][$col].Int} , ^$SIZE } | |
sub neighbours(@p , $row,$col) { | |
my ($grid_x,$grid_y) = map {($_/3).Int} ,($row,$col); | |
my @locations = (($grid_x*3..$grid_x*3+2) X=> ($grid_y*3..$grid_y*3+2)); | |
#~ die @locations.perl; | |
return map { @p[.key][.value].Int } , @locations; | |
} | |
sub get-states-for (@p , $x , $y) { | |
return @p[$x][$y].Int if @p[$x][$y] && @p[$x][$y] !~~ Junction; | |
#~ return @puzzle[$x][$y].Int if @puzzle[$x][$y] ~~ Junction; #TODO:Fix me | |
my @cannot-be = ( | |
cols(@p,$x,$y) , | |
rows(@p,$x,$y) , | |
neighbours(@p,$x,$y) | |
) ; | |
@cannot-be = grep {$_ ~~ Int} , @cannot-be; | |
return eigenstates(none(|@cannot-be)); | |
} | |
sub solve (@p is rw) { | |
while $FOUND_NEW_STUFF { | |
say "-- New squares filled ... New Round required --"; | |
$FOUND_NEW_STUFF = False; | |
for ^$SIZE X ^$SIZE -> $x,$y { | |
@p[$x][$y] = get-states-for(@p,$x,$y); | |
#~ say "$x,$y => " , @p[$x][$y]; | |
} | |
} | |
@p.join("\n").say; | |
} | |
my @puzzle = | |
[<0 0 3 0 2 0 6 0 0>], | |
[<9 0 0 3 0 5 0 0 1>], | |
[<0 0 1 8 0 6 4 0 0>], | |
[<0 0 8 1 0 2 9 0 0>], | |
[<7 0 0 0 0 0 0 0 8>], | |
[<0 0 6 7 0 8 2 0 0>], | |
[<0 0 2 6 0 9 5 0 0>], | |
[<8 0 0 2 0 3 0 0 9>], | |
[<0 0 5 0 1 0 3 0 0>], | |
; | |
solve(@puzzle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment