PatternSolver/Generator.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« PatternSolver/CPLogic.pm ↑ Summary PatternSolver/Patterns.pm »
1 package Games::Sudoku::PatternSolver::Generator;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 require 5.06.0;
7  
8 0 ▶use Games::Sudoku::PatternSolver::Patterns qw( init_patterns );
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Games::Sudoku::PatternSolver qw( solve print_grid );
10  
11 use Bit::Vector;
12 use List::Util qw( shuffle );
13 use Time::HiRes ();
14  
15 our @ISA = qw( Exporter );
16 our @EXPORT_OK = qw( get_sudoku_builder get_grid_builder print_grid );
17 our %EXPORT_TAGS = (
18 'all' => \@EXPORT_OK,
19 );
20  
21 our $VERBOSE = 0;
22 our $LOOSE_MODE = 0; # whether to allow puzzles to have < 8 different givens (still with an unique solution)
23  
24 ###########################################################
25  
26 {
27 my $grid_builder;
28  
29 # the grid at start doesn't matter for quality of the individual puzzle generated,
30 # but all puzzles generated from a single static grid share the same solution
31 sub get_sudoku_builder {
32 my ($start_grid_string, $start_with, $shuffle_symbols) = @_;
33  
34 set_solver_config();
35  
36 if ($start_grid_string) {
37 my $sudoku = solve($start_grid_string)
38 or return 0;
39  
40 my $sc = $sudoku->{solutionCount};
41  
42 if ($sc != 1) {
43 printf "No way to reduce: Start grid %s and is invalid!\n", ($sc > 1) ? 'already has more than one solutions' : 'has NO solution';
44 return 0;
45 }
46 }
47  
48 my $check_reducibility = ($start_grid_string && $start_grid_string =~ /[^1-9]/) ? 1 : 0;
49  
50 $start_with = 40 unless defined($start_with);
51 $shuffle_symbols = 1 unless defined($shuffle_symbols);
52  
53 $grid_builder ||= get_grid_builder();
54 my $next_grid_str = $start_grid_string || &$grid_builder($shuffle_symbols);
55  
56 return sub {
57 # given a possible solution, reduce the given values in random order until a proper sudoku is found that cannot be further reduced
58 # (searching for a rating > 0.65 may take a while)
59  
60 # my $old_handler = $SIG{INT};
61 # local $SIG{INT} = set_exit_handler(sub {print "BOOO!\n", &$old_handler() if ref($old_handler);});
62 #my $solve_tries = 0;
63  
64 while (1) {
65 print ">>> '$next_grid_str'\n" if $VERBOSE;
66 # the initially given grid may have been fleshed out already
67 my $grid = [split //, $next_grid_str];
68 my @start_positions = map { $grid->[$_] =~ /[1-9]/ ? $_ : () } (0..$#$grid);
69 #@start_positions >= 17 or die "Trying to reduce ", scalar(@start_positions), " givens from '$next_grid_str' is pretty much senseless.\n";
70 my $to_drop = @start_positions - $start_with;
71 $to_drop = 0 if $to_drop < 0;
72  
73 my $fields_to_try = $check_reducibility ? [@start_positions] : [shuffle @start_positions];
74  
75 # to get going, start from a certain depth
76 my $dropped_fields = [];
77 ($to_drop && !$check_reducibility) and do {
78 drop_values($grid, $to_drop, $fields_to_try, $dropped_fields)
79 or die "Couldn't drop $to_drop givens from the grid (@$grid).\n"
80 };
81  
82 my $to_be_reduced;
83 my $solution_count = 0;
84  
85 while ($solution_count < 2) {
86 unless (drop_values($grid, 1, $fields_to_try, $dropped_fields)) {
87 # tried to drop any single field that was left so far (bar 17), all leading to > 1 solutions => not further reducible => start over
88 if ($to_be_reduced) {
89 $next_grid_str = $start_grid_string || &$grid_builder($shuffle_symbols);
90 $check_reducibility = 0;
91  
92 # this returns always a multiple of 40 (40 - 320 .. ??) why ???
93 #print $solve_tries, " tries to solve were needed.\n";
94  
95 return $to_be_reduced;
96  
97 } elsif ($check_reducibility && !$to_be_reduced) {
98 print "$solution_count: Start grid is minimal (could not be reduced): '$next_grid_str'\n";
99 return 0;
100 }
101 last;
102 }
103  
104 my $sudoku = solve($grid)
105 or last;
106 #$solve_tries++;
107 $solution_count = $sudoku->{solutionCount};
108 print "sc=$solution_count\n" if $VERBOSE;
109  
110 if ($solution_count == 1) {
111 if ((!$to_be_reduced) || ($to_be_reduced->{uniqueGivens} > $sudoku->{uniqueGivens}) || ($to_be_reduced->{givensCount} >= $sudoku->{givensCount})) {
112 # most interesting (reduced) puzzle found in the given start grid so far,
113 # still a subject to possible minimization
114 $to_be_reduced = $sudoku;
115 }
116 next;
117 }
118  
119 unless ($solution_count == 2) {
120 warn "The current grid seems unsolvable!\n"; # . Dumper($sudoku);
121 return 0;
122 }
123  
124 # return to the former state (solution count == 1)
125 # and try to achieve further reduction by dropping another value instead
126 reinsert_last_value($grid, $dropped_fields);
127 $solution_count = 1;
128 }
129  
130 if ($check_reducibility) {
131 $check_reducibility = 0;
132 print "Reducibility check finished.\n";
133 return 0;
134 }
135  
136 $next_grid_str = $start_grid_string || &$grid_builder($shuffle_symbols);
137 }
138  
139 return 0
140 };
141 }
142 }
143  
144 sub drop_values {
145 my ($grid, $to_drop, $fields_to_try, $dropped) = @_;
146  
147 my $dropped_count = 0;
148 while ( $dropped_count < $to_drop ) {
149 my $field_index = shift @$fields_to_try;
150 return $dropped_count unless defined($field_index);
151 my $symbol = $grid->[$field_index];
152 print "dropped $symbol from $field_index\n" if $VERBOSE;
153 die "Unexpected symbol '$symbol' in position $field_index!" if (!$symbol || $symbol eq '.');
154 $grid->[$field_index] = '.';
155 push @$dropped, [$field_index, $symbol];
156 $dropped_count++;
157 }
158  
159 return $dropped_count;
160 }
161  
162 sub reinsert_last_value {
163 # only puts the value back into the grid, does not return the index into the queue of drop candidates
164 my ($grid, $dropped) = @_;
165  
166 my ($field_index, $symbol) = @{pop @$dropped} or die "No more grid positions to restore!";
167 $grid->[$field_index] = $symbol;
168 print "restored $symbol at $field_index\n" if $VERBOSE;
169 }
170  
171 sub set_solver_config {
172 # fastest way to find out if a sudoku has 0, 1, or more solutions
173 $Games::Sudoku::PatternSolver::VERBOSE = $VERBOSE;
174 $Games::Sudoku::PatternSolver::MAX_SOLUTIONS = 2;
175 $Games::Sudoku::PatternSolver::LOOSE_MODE = $LOOSE_MODE;
176 $Games::Sudoku::PatternSolver::USE_LOGIC = 1;
177 }
178  
179 ###########################################################
180  
181 {
182 my $patterns_by_field;
183  
184 sub get_grid_builder {
185  
186 $patterns_by_field ||= (init_patterns())[0];
187  
188 shuffle_pattern_arrays($patterns_by_field);
189  
190 # creating 81 iterators; each one iterates over a circular list with 5184 vectors in random order, which all have the specified field bit in common
191 my %pattern_iterators = ();
192 foreach my $field_index (keys %$patterns_by_field) {
193 my $list = $patterns_by_field->{$field_index};
194 my $index = -1;
195 $pattern_iterators{$field_index} = sub {
196 $index++;
197 $index = 0 if $index > $#$list;
198 return $list->[ $index ];
199 };
200 }
201  
202 my $test_vector = Bit::Vector->new(81);
203  
204 return sub {
205 my $shuffle_symbols = shift() || 0;
206  
207 local $SIG{'INT'} = set_exit_handler();
208  
209 while (1) {
210 my @placed_vectors = ();
211 my $coverage_vector = Bit::Vector->new(81);
212 my $placed = 0;
213
214 while ($placed < 9) {
215 $test_vector->Not($coverage_vector);
216 my $any_empty_field = $test_vector->Min();
217  
218 my $could_place = 0;
219 for (my $i = 0; $i < 5184; $i++) {
220 my $pattern_vector = $pattern_iterators{$any_empty_field}();
221 $test_vector->And($coverage_vector, $pattern_vector);
222  
223 if ($test_vector->is_empty()) {
224 $coverage_vector->Or($coverage_vector, $pattern_vector);
225 push @placed_vectors, $pattern_vector;
226 $placed++;
227 $could_place = 1;
228 last;
229 }
230 }
231 $could_place or last;
232 }
233  
234 ($placed == 9) and return join '', prepare_grid(\@placed_vectors, $shuffle_symbols);
235 }
236 };
237 }
238  
239 sub prepare_grid {
240 # an arrayref with 9 complementing bit vectors
241 my ($pattern_stack, $do_shuffle) = @_;
242  
243 # having 1-9 assigned to the 1st row makes spotting eventual repetitions more easy
244 my @symbols = $do_shuffle ? (shuffle 1..9) : 1..9;
245
246 my @chars = ();
247 foreach my $pattern_vector (@$pattern_stack) {
248 my $symbol = shift @symbols;
249 $chars[$_] = $symbol for $pattern_vector->Index_List_Read();
250 }
251  
252 return @chars
253 }
254  
255 sub shuffle_pattern_arrays {
256 my ($HashOfArrays) = @_;
257  
258 my $t1 = Time::HiRes::time();
259 foreach my $key (keys %$HashOfArrays) {
260 @{$HashOfArrays->{$key}} = shuffle( @{$HashOfArrays->{$key}} );
261 }
262 printf("Shuffling patterns took %0.4f secs.\n", Time::HiRes::time() - $t1) if $VERBOSE;
263 }
264 }
265  
266 sub set_exit_handler {
267 my ($sub_to_execute) = @_;
268  
269 return $Games::Sudoku::PatternSolver::exitHandler = sub {
270 #print "Exit on user request.\n";
271 &$sub_to_execute if $sub_to_execute;
272 #Time::HiRes::sleep 0.2;
273 #CORE::exit(0);
274 };
275 }
276  
277 1
278  
279 __END__
« PatternSolver/CPLogic.pm ↑ Summary PatternSolver/Patterns.pm »