Created
August 9, 2011 12:03
-
-
Save Takadonet/1133863 to your computer and use it in GitHub Desktop.
attribute not being set...
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
class SudokuSolver { | |
has Int @!grid is rw; | |
method build(Str $s) { | |
@!grid = $s.comb(); | |
} | |
method solve() { | |
self.placeNumber(0); | |
} | |
method placeNumber(Int $pos) { | |
if ($pos == 81) { | |
say 'final placeNumber and returning'; | |
self.toString().say; | |
@!grid[0]=5; | |
return True; | |
} | |
if (@!grid[$pos] > 0) { | |
self.placeNumber($pos + 1); | |
return True; | |
} | |
for (1..9) -> $n { | |
if (self.checkValidity($n, $pos % 9, ($pos / 9).Int) ) { | |
@!grid[$pos] = $n; | |
self.placeNumber($pos + 1); | |
@!grid[$pos] = 0; | |
} | |
} | |
return True; | |
} | |
method checkValidity(Int $val, Int $x, Int $y) { | |
for ^9 -> $i { | |
if (@!grid[$y * 9 + $i] == $val || @!grid[$i * 9 + $x] == $val) { | |
return False; | |
} | |
} | |
my Int $startX = ($x / 3).Int * 3; | |
my Int $startY = ($y / 3).Int * 3; | |
loop (my Int $a = $startY; $a < $startY + 3; $a++) { | |
loop (my Int $j = $startX; $j < $startX + 3; $j++) { | |
if (@!grid[$a * 9 + $j] == $val) { | |
return False; | |
} | |
} | |
} | |
return True; | |
} | |
method toString() { | |
my Str $sb; | |
for ^9 -> $i { | |
for ^9 -> $j { | |
$sb ~= @!grid[$i * 9 + $j] ~ ' '; | |
if ($j == 2 | 5) { | |
$sb ~="| "; | |
} | |
} | |
$sb ~= "\n"; | |
if ($i == 2 | 5) { | |
$sb ~= "------+-------+------\n"; | |
} | |
} | |
return $sb; | |
} | |
} | |
my $x =SudokuSolver.new(); | |
$x.build('034167598' ~ | |
'198543627' ~ | |
'765982431' ~ | |
'987036215' ~ | |
'653219874' ~ | |
'421758069' ~ | |
'819625743' ~ | |
'542371986' ~ | |
'376894150'); | |
$x.toString().say; | |
$x.solve(); | |
say 'outside placeNumber'; | |
$x.toString().say; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment