PatternSolver.pm

filter: Statementstmt 33.3% 1 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 50.0% 2 / 4 CC 1 SCAR 2.6
CC
1
Cov
33%
BEGIN
1.3
CRAP 1.3
↑ Summary PatternSolver/CPLogic.pm »
1 package Games::Sudoku::PatternSolver;
2  
3 our $VERSION = '0.07';
4  
5 require 5.06.0;
6  
7 0 ▶use Bit::Vector qw();
Subroutine BEGIN: called CC=1 SCAR=2.6
8 use Time::HiRes qw();
9  
10 use Games::Sudoku::PatternSolver::Patterns qw( init_patterns );
11  
12 use strict;
13 use warnings;
14  
15 our @ISA = qw( Exporter );
16 our @EXPORT_OK = qw( solve print_solution print_grid $VERBOSE $MAX_SOLUTIONS $LOOSE_MODE $USE_LOGIC );
17 our %EXPORT_TAGS = (
18 'all' => \@EXPORT_OK,
19 );
20  
21 our $VERBOSE = 0; # Informative output about the algorithm at work
22 our $MAX_SOLUTIONS = 2; # If 0, will do an exhaustive search which may run into memory problems on invalid puzzles. (Time overhead isn't very much, usally.)
23 our $LOOSE_MODE = 1; # Finds the unique solution even for any sudoku with < 8 different givens, using letters as dropin symbols.
24 our $USE_LOGIC = 1; # Try to fill in more givens before starting with patterns? Only uses simple area constraints (naked / hidden singles).
25  
26 ####################################################################
27 our $exit_handler;
28  
29 {
30 my ($patterns_by_field, $all_patterns) = init_patterns();
31  
32 sub solve {
33 my $str_puzzle = ((ref $_[0]) ? flatten_input(@_) : join('', @_))
34 or die " - dunno how to handle that input ... :-(\n";
35  
36 length($str_puzzle) == 81 or die "Puzzle input must be 81 chars long.\n";
37 $str_puzzle =~ s/[ 0]/./g; # dots, not zeros for free cells
38  
39 print_grid($str_puzzle) if $VERBOSE;
40  
41 my $start_time = Time::HiRes::time();
42  
43 my $puzzle = new_puzzle(
44 startTime => $start_time,
45 strPuzzle => $str_puzzle
46 ) or return 0;
47  
48 if ($USE_LOGIC) {
49 require Games::Sudoku::PatternSolver::CPLogic;
50 Games::Sudoku::PatternSolver::CPLogic::apply_logic( $puzzle )
51 or return 0;
52  
53 my $logic_endtime = Time::HiRes::time();
54 my $logic_time = $logic_endtime - $start_time;
55  
56 if ($puzzle->{logicFilled}) {
57 printf("Logic mode provided %d more clues after %0.6f secs:", $puzzle->{logicFilled}, $logic_time) if $VERBOSE;
58  
59 $str_puzzle = $puzzle->{strPuzzleAfterLogic};
60 print_grid($str_puzzle) if $VERBOSE;
61 }
62  
63 if ($puzzle->{logicSolved}) {
64 print "Puzzle was solved by logic alone (no backtracking with patterns needed)!\n" if $VERBOSE;
65 $puzzle->{seconds} = $logic_time;
66 $puzzle->{endTime} = $logic_endtime;
67  
68  
69 ### TODO: Logic will only ever find the 1st solution. How to ensure a valid puzzle?
70 return $puzzle
71 }
72 }
73  
74 set_exit_handler($exit_handler);
75  
76 solve_puzzle($puzzle, $patterns_by_field, $all_patterns)
77 or return 0;
78  
79 restore_exit_handler();
80  
81 $puzzle->{endTime} = Time::HiRes::time();
82 $puzzle->{seconds} = $puzzle->{endTime} - $puzzle->{startTime};
83  
84 sweep($puzzle);
85  
86 return $puzzle
87 }
88 }
89  
90 ####################################################################
91  
92 sub flatten_input {
93 my $input = $_[0];
94  
95 my $ref = ref($input) or return 0;
96  
97 if ($ref eq 'ARRAY') {
98 if ($#$input == 80 && (defined $input->[0]) && (not ref($input->[0]))) {
99 return join '', @$input;
100 }
101  
102 if ($#$input == 8 && (defined $input->[0]) && (ref($input->[0]) eq 'ARRAY') && ($#$input->[0] == 8)) {
103 # AoA 9x9
104 return join( '', map {join( '', @$_)} @$input);
105 }
106 }
107  
108 return undef
109 }
110  
111 sub solve_puzzle {
112 # apply backtracking
113 my ($puzzle, $patterns_by_field, $all_patterns) = @_;
114  
115 my $symbol_vectors = $puzzle->{symbolVectors};
116 my $symbol_counts = $puzzle->{symbolCounts};
117  
118 # so far, only symbols with at least 1 given appear here
119 my @by_count = sort {((defined($symbol_counts->{$b}) ? $symbol_counts->{$b} : 0) <=> (defined($symbol_counts->{$a}) ? $symbol_counts->{$a} : 0)) || ($a cmp $b)} keys %$symbol_counts;
120  
121 my $no_clue_patterns;
122 if ($USE_LOGIC) {
123 foreach my $symbol (1 .. 9) {
124 unless (exists $symbol_counts->{$symbol}) {
125 # all clueless symbols share the same candidate positions
126 my $no_clue_candidates = $puzzle->{candidateVectors}{$symbol};
127 $no_clue_patterns = [map {$_->subset($no_clue_candidates) ? $_ : ()} @$all_patterns];
128 last;
129 }
130 }
131 }
132 $no_clue_patterns ||= $all_patterns;
133  
134 if ($LOOSE_MODE && @by_count < 8) {
135 # with less than 8 different givens, we have to stock up on distinguishing cell markers
136 my @dropins = ('A' .. 'I');
137 while (@by_count < 9) {
138 my $dropin_symbol = shift @dropins;
139 push @by_count, $dropin_symbol;
140 $symbol_counts->{$dropin_symbol} = 0;
141 $symbol_vectors->{$dropin_symbol} = Bit::Vector->new(81);
142 }
143 }
144 $puzzle->{maxDepth} = $#by_count;
145  
146 my $test_vector = Bit::Vector->new(81);
147  
148 my %possible_solutions = ();
149 my $invalid = 0;
150  
151 foreach my $symbol (@by_count) {
152 my $symbol_vector = $symbol_vectors->{$symbol}
153 or die "No vector for givens '$symbol'!\n";
154  
155 my $t2 = Time::HiRes::time();
156  
157 my $pre_filtered;
158  
159 if ($symbol_counts->{$symbol} == 9) {
160 $pre_filtered = [$symbol_vector];
161  
162 } elsif ($symbol_counts->{$symbol} > 0) {
163 # start with a reduced set of 5184 instead of 46656 possible distributions for this symbol
164 my $any_given_field = $symbol_vector->Min();
165  
166 if ($USE_LOGIC) {
167 # a chance to early prune patterns by subsetting them against their resp. candidate map
168 my $allowed_positions = Bit::Vector->new(81);
169 $allowed_positions->Or($symbol_vector, $puzzle->{candidateVectors}{$symbol});
170 $pre_filtered = [map {$_->subset($allowed_positions) ? $_ : ()} @{$patterns_by_field->{$any_given_field}}];
171  
172 } else {
173 $pre_filtered = $patterns_by_field->{$any_given_field};
174 }
175  
176 } else {
177 # no givens -> a general prefilterung by shared candidates happened above
178 $pre_filtered = $no_clue_patterns;
179 }
180  
181 my @solutions = ();
182 my $found = 0;
183 my $omitted = 0;
184  
185 foreach my $pattern_vector (@$pre_filtered) {
186 if ($symbol_vector->subset($pattern_vector)) {
187 $found++;
188  
189 # early omittance of patterns wherever a non-conflicting pattern was not found for any of the former symbols
190 my $outer = 1;
191 foreach my $symbol_2 (keys %possible_solutions) {
192 my $inner = 0;
193 foreach my $pattern_vector_2 (@{$possible_solutions{$symbol_2}}) {
194 $test_vector->And($pattern_vector, $pattern_vector_2);
195 if ($test_vector->is_empty()) {
196 # fits to at least one of that other symbol's pattern candidates
197 # proceed to testing next symbol's candidates
198  
199 $inner = 1;
200 last;
201 }
202 }
203  
204 unless($inner) {
205 $outer = 0;
206 last;
207 }
208 }
209  
210 if ($outer) {
211 push @solutions, $pattern_vector;
212  
213 } else {
214 $omitted++;
215 }
216  
217 }
218 }
219  
220 unless ($found - $omitted) {
221 print "Givens '$symbol' have no pattern match, puzzle is invalid!\n";
222 $invalid++;
223 }
224  
225 $possible_solutions{$symbol} = \@solutions;
226 printf(" Symbol '%s' (%d givens) %5d assigned -> %4d kept (%4d omitted) in %f secs\n",
227 $symbol, $symbol_counts->{$symbol}, $found, $found - $omitted, $omitted, Time::HiRes::time() - $t2) if $VERBOSE;
228 }
229  
230 return 0 if $invalid;
231  
232 # in a 2nd step, further reduce the number of patterns
233 print("Reverse elimination of pattern candidates:\n") if $VERBOSE;
234 reverse_filter(\@by_count, \%possible_solutions, $symbol_counts);
235  
236 printf("Start backtracking for possible pattern combinations after %0.5f secs:\n", Time::HiRes::time() - $puzzle->{startTime}) if $VERBOSE;
237 find_solutions(0, \@by_count, \%possible_solutions, Bit::Vector->new(81), {}, $puzzle);
238  
239 return 1
240 }
241  
242 sub reverse_filter {
243 # try to eliminate even more patterns by doing the fitting test in reverse order
244 my ($by_count, $possible_solutions, $symbol_counts) = @_;
245  
246 my $test_vector = Bit::Vector->new(81);
247  
248 # starting out on patterns for the most abundant symbol, removing those who have no non-conflicting counterpart for any of the rarer symbols
249  
250 for (my $symbol_index_1 = 0; $symbol_index_1 < $#$by_count; $symbol_index_1++) {
251 my $symbol_1 = $by_count->[$symbol_index_1];
252 my $solutions_1 = $possible_solutions->{$symbol_1};
253 my $found = 0;
254 my $omitted = 0;
255  
256 my $t2 = Time::HiRes::time();
257 my @filtered_solutions = ();
258  
259 foreach my $pattern_vector_1 (@$solutions_1) {
260 $found++;
261  
262 my $outer = 1;
263 for (my $symbol_index_2 = $symbol_index_1 + 1; $symbol_index_2 <= $#$by_count; $symbol_index_2++) {
264 my $symbol_2 = $by_count->[$symbol_index_2];
265 my $solutions_2 = $possible_solutions->{$symbol_2};
266  
267 my $inner = 0;
268 foreach my $pattern_vector_2 (@$solutions_2) {
269 $test_vector->And($pattern_vector_1, $pattern_vector_2);
270 if ($test_vector->is_empty()) {
271 # fits to at least one of that 2nd symbol's pattern candidates
272 # proceed to testing the outer symbol's next candidate
273 $inner = 1;
274 last;
275 }
276 }
277  
278 unless($inner) {
279 $outer = 0;
280 last;
281 }
282 }
283  
284 if ($outer) {
285 push @filtered_solutions, $pattern_vector_1;
286  
287 } else {
288 $omitted++;
289 }
290 }
291 $possible_solutions->{$symbol_1} = \@filtered_solutions;
292 printf(" Symbol '%s' (%d givens) %4d -> %4d were kept (%4d omitted) in %f secs\n",
293 $symbol_1, $symbol_counts->{$symbol_1}, $found, $found - $omitted, $omitted, Time::HiRes::time() - $t2) if $VERBOSE;
294 }
295 }
296  
297 # the essential recursive function of the solver
298 # the return value signals whether to abort (false) or proceed (true) with the backtracking
299 sub find_solutions {
300 my ($depth, $symbols, $possibles, $coverage_vector, $current_pattern_vectors, $puzzle) = @_;
301  
302 $depth > $puzzle->{maxDepth}
303 and die sprintf("FIX ME: depth=$depth (maxDepth = %d)\n", $puzzle->{maxDepth});
304  
305 my $symbol = $symbols->[$depth];
306  
307 my $test_vector = Bit::Vector->new(81);
308 foreach my $pattern_vector (@{$possibles->{$symbol}}) {
309 $test_vector->And($coverage_vector, $pattern_vector);
310  
311 if ($test_vector->is_empty()) {
312 # no conflicts
313 $current_pattern_vectors->{$symbol} = $pattern_vector;
314 $coverage_vector->Or($coverage_vector, $pattern_vector);
315  
316 if ($depth == $puzzle->{maxDepth}) {
317 # is it a proper new solution?
318 # because patterns are tried in random order and one pattern can be tried for different symbols, repetitive solutions have to be avoided
319 my $newSolutionKey = solution_is_new($puzzle, $current_pattern_vectors);
320 if ($newSolutionKey) {
321 my $solution_string = prepare_solution_string($symbols, $current_pattern_vectors);
322 add_solution($puzzle, $newSolutionKey, $solution_string);
323 print_solution($solution_string, $puzzle->{solutionCount}, $puzzle->{startTime}) if $VERBOSE;
324 check_for_max_solutions($puzzle->{solutionCount}) or return 0;
325 }
326  
327 } else {
328 # descent, and bubble up a false return value
329 find_solutions ($depth+1, $symbols, $possibles, $coverage_vector, $current_pattern_vectors, $puzzle)
330 or return 0;
331 }
332 # remove this pattern and proceed on the same level
333 delete $current_pattern_vectors->{$symbol};
334 $coverage_vector->Xor($coverage_vector, $pattern_vector);
335 }
336 }
337  
338 return 1
339 }
340  
341 sub prepare_solution_string {
342 my ($symbols, $pattern_vectors) = @_;
343  
344 my @chars = ('0') x 81;
345  
346 for (my $symbol_index = 0; $symbol_index < 9; $symbol_index++) {
347 my $symbol = $symbols->[$symbol_index];
348 defined($symbol) or last;
349 my $symbol_vector = $pattern_vectors->{$symbol} or last;
350 $chars[$_] = $symbol for $symbol_vector->Index_List_Read();
351 }
352  
353 return join '', @chars
354 }
355  
356 sub print_solution {
357 my ($solution, $solution_nr, $startTime) = @_;
358
359 printf("\nSolution #%d after %f secs:", $solution_nr, Time::HiRes::time() - $startTime) if $VERBOSE && $solution_nr && $startTime;
360  
361 $solution =~ s/[^1-9A-I]/ /g;
362 print_grid($solution);
363 }
364  
365 sub print_grid {
366 my $grid_string = shift;
367 my @symbols = split //, $grid_string;
368  
369 my $row_count = 0;
370 print "\n-------------------------\n";
371 while (my @row = splice @symbols, 0, 9) {
372 while (my @triple = splice @row, 0, 3) {
373 print "| @triple ";
374 }
375 print(++$row_count % 3 ? "|\n" : "|\n-------------------------\n");
376 }
377 }
378  
379 sub check_for_max_solutions {
380 my $solution_count = shift;
381  
382 if ($MAX_SOLUTIONS) {
383 if ($solution_count >= $MAX_SOLUTIONS) {
384 print "\$MAX_SOLUTIONS=$MAX_SOLUTIONS are reached - exiting.\n" if $VERBOSE;
385 return 0;
386 }
387 }
388  
389 return 1
390 }
391  
392 {
393 # prevent error messages in windows, if user break happens inside a nested call
394 my $old_handler;
395  
396 sub set_exit_handler {
397 my ($sub_to_execute) = @_;
398 return if $Games::Sudoku::PatternSolver::exitHandler;
399 $old_handler and return;
400  
401 $old_handler = $SIG{'INT'};
402 $SIG{'INT'} = $Games::Sudoku::PatternSolver::exitHandler = sub {
403 print "Exit on user request.\n";
404 &$sub_to_execute if $sub_to_execute;
405 CORE::exit(0);
406 };
407 }
408  
409 sub restore_exit_handler {
410 if ($old_handler) {
411 $SIG{'INT'} = $old_handler;
412 $old_handler = undef;
413 }
414 }
415 }
416  
417 ###############################################################
418  
419 sub new_puzzle {
420  
421 return _read_puzzle({
422 startTime => 0,
423 strPuzzle => undef,
424 @_,
425  
426 endTime => 0,
427 seconds => 0,
428  
429 # properties and state keeping
430 maxDepth => undef,
431 symbolVectors => undef,
432 givensCount => undef,
433 uniqueGivens => undef,
434 countsByGivens => undef, # at start, on puzzle init
435 symbolCounts => undef, # a copy that reflects the current state
436  
437 # logic mode related, might get used for ratings
438 logicFilled => 0,
439 candidatesDropped => 0,
440 logicSteps => [],
441 logicSolved => 0,
442  
443 # backtracking related
444 rejectedCount => 0,
445 knownSolutions => {},
446  
447 solutions => [],
448 solutionCount => 0,
449 })
450 }
451  
452 sub _read_puzzle {
453 my ($puzzle) = @_;
454  
455 my $puzzle_string = $puzzle->{strPuzzle}
456 or die "Named param 'strPuzzle' must be passed to new_puzzle()";
457  
458 my $givens = 0;
459 my %counts = ();
460 my %symbol_vectors = ();
461 @symbol_vectors{1..9} = Bit::Vector->new(81, 9);
462  
463 my $field_offset = 0;
464 foreach my $symbol (split //, $puzzle_string) {
465 if ($symbol =~ /[1-9]/) {
466 $givens++;
467 $counts{$symbol}++;
468 $symbol_vectors{$symbol}->Bit_On($field_offset);
469 }
470 $field_offset++;
471 }
472  
473 $puzzle->{symbolVectors} = \%symbol_vectors;
474 $puzzle->{givensCount} = $givens;
475 $puzzle->{uniqueGivens} = scalar keys %counts;
476 $puzzle->{countsByGivens} = \%counts;
477 $puzzle->{symbolCounts} = {%counts};
478  
479 print("Puzzle has $puzzle->{uniqueGivens} different symbols.\n") if $VERBOSE;
480  
481 if ($puzzle->{uniqueGivens} < 5) {
482 warn "Puzzle has $puzzle->{uniqueGivens} different symbols and cannot have a unique solution.\n";
483 return 0;
484  
485 } elsif ($puzzle->{uniqueGivens} < 8 && ! $LOOSE_MODE) {
486 warn "Puzzle has $puzzle->{uniqueGivens} different symbols and may be solved with \$LOOSE_MODE=1 only.\n";
487 return 0;
488 }
489  
490 if ($puzzle->{givensCount} < 17) {
491 warn "Puzzle has $puzzle->{givensCount} givens while 17 is regarded as bare minimum for a unique solution.\n";
492 return 0;
493 }
494  
495 return $puzzle
496 }
497  
498 sub sweep {
499 my ($puzzle, $thorough) = @_;
500  
501 $thorough = 1 unless defined($thorough);
502  
503 if ($thorough) {
504 delete $puzzle->{$_} for qw(
505 maxDepth
506 symbolVectors
507 symbolCounts
508 rejectedCount
509 knownSolutions
510 );
511  
512 } else {
513 $puzzle->{knownSolutions} = {};
514 $puzzle->{symbolVectors} = undef;
515 }
516  
517 return $puzzle
518 }
519  
520 sub add_solution {
521 my ($puzzle, $key, $solution) = @_;
522  
523 $puzzle->{knownSolutions}{$key} = undef;
524 push @{$puzzle->{solutions}}, $solution;
525  
526 return $puzzle->{solutionCount}++
527 }
528  
529 sub solution_is_new {
530 my ($puzzle, $vectors) = @_;
531  
532 # the hash values are the current Bit::Vector objects, found to satisfy the puzzle
533 # here we create a short, unique key with the addresses of these up to 9 vectors
534 my $key = join '|', sort map {/0x(.+?)\)$/} values %$vectors;
535  
536 if (exists $puzzle->{knownSolutions}{$key}) {
537 $puzzle->{rejectedCount}++;
538 return undef;
539 }
540  
541 return $key
542 }
543  
544 1
545  
↑ Summary PatternSolver/CPLogic.pm »