Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

proper constraint tracking; simple (not yet active) solving

  • Loading branch information...
commit df7f317bd508d9f8e80e97cbbae75ad1316d2c1e 1 parent de392cd
Moritz Lenz authored
Showing with 51 additions and 12 deletions.
  1. +47 −11 lib/Sudoku.pm
  2. +4 −1 test.pl
58 lib/Sudoku.pm
View
@@ -4,19 +4,31 @@ class Sudoku::Constraint {
has @.x;
has @.y; # ;;
has %.remaining-symbols handles delete-symbol => 'delete';
+ method xy() { @!x Z @!y };
+ method Str {
+ ' Constraint: x(' ~ @!x ~ '); y(' ~ @!y ~ ') '
+ ~ %!remaining-symbols.keys.sort
+ ~ "\n";
+ }
}
class Sudoku {
has $.block-size = 3;
has $.size = $.block-size ** 2;
has @.rows;
+ has @!coverage;
- has @!maybe;
- has @!constraints;
+ has @.constraints;
method from-string($s) {
- my $o = self.new(rows => $s.comb(/.**9/).map: { [ .comb.map: +* ] });
+ my $o = self.new(rows => (^9).map: {[0 xx 9]});
$o.init();
+ for ^$o.size X ^$o.size -> $y, $x {
+ my $i = 9 * $y + $x;
+ if $s.substr($i, 1) -> $char {
+ $o.add-hint($char, :$x, :$y);
+ }
+ }
$o;
}
@@ -24,23 +36,19 @@ class Sudoku {
@!rows.map({ .map({ $_ == 0 ?? '.' !! $_ }).join ~ "\n" }).join;
}
- method add-number($n, :$x, :$y) {
+ method add-hint($n, :$x, :$y) {
given @!rows[$y][$x] {
if $_ && $_ !== $n {
die "Trying to set ($x, $y) to $n, but it is already set (to $_)";
}
}
- @!constraints[$y][$y] = [0 xx $!size];
- for ^$!size {
- @!constraints[$y][$_][$n - 1] = 0;
- @!constraints[$_][$x][$n - 1] = 0;
+ @!rows[$y][$x] = $n;
+ for @(@!coverage[$y][$x]) {
+ .delete-symbol($n);
}
}
method init() {
- for ^$!size X ^$!size -> $x, $y {
- @!constraints[$y][$x] = [ True xx $!size ];
- }
for ^$!size {
# rows
@!constraints.push: Sudoku::Constraint.new(
@@ -56,12 +64,40 @@ class Sudoku {
);
}
for ^$!block-size X ^$!block-size -> $x, $y {
+ # blocks
@!constraints.push: Sudoku::Constraint.new(
x => (^$!block-size X+ ($x * $!block-size)) xx $!block-size,
y => ((^$!block-size Xxx $!block-size )X+ ($y * $!block-size)),
remaining-symbols => hash( 1..$!size Z=> True xx * ),
);
}
+ for @!constraints -> $c {
+ for $c.xy -> $x, $y {
+ @!coverage[$y][$x] //= [];
+ @!coverage[$y][$x].push: $c;
+ }
+ }
+ }
+
+ method solve() {
+ $.simple-fill();
+ }
+
+ method simple-fill() {
+ for @!constraints -> $c {
+ my @rc = $c.remaining-symbols.keys;
+ if @rc == 1 {
+ # just one remaining symbol
+ # find out where it is
+ for $c.xy -> $x, $y {
+ if @!rows[$y][$x] == 0 {
+ say "Adding @rc[0] to ($x, $y)";
+ $.add-hint(@rc[0], :$x, :$y);
+ last;
+ }
+ }
+ }
+ }
}
}
5 test.pl
View
@@ -19,4 +19,7 @@
my $s = Sudoku.from-string($puzzle);
say $s;
-say $s.perl;
+say $s.constraints;
+$s.solve();
+say $s;
+#say $s.perl;
Please sign in to comment.
Something went wrong with that request. Please try again.