lib/Games/Sudoku/Trainer/Strategies.pm untested

filter: Statementstmt 0.0% 0 / 525 Branchbran 0.0% 0 / 178 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 889 CC 90 SCAR 39.3
CC
90
Cov
0%
_turbot_fish
110.0
_two_string_kite
110.0
_skyscraper
90.0
CRAP 50.8
1 use strict;
2 use warnings;
3 #use feature 'say';
4
5 # basic Sudoku structures
6 # don't panic - all basic Sudoku structures are constant
7 package main;
8 our @cells; # cell objects (1 .. 81)
9 our @rows; # row objects (1 .. 9)
10 our @cols; # col objects (1 .. 9)
11 our @blocks; # block objects (1 .. 9)
12 our @units; # all unit objects (0 .. 26) rows, columns, and blocks
13 our @lines; # all line objects (0 .. 17) rows and columns
14
15 package
16 Games::Sudoku::Trainer::Strategies;
17
18 use version; our $VERSION = qv('0.04'); # PBP
19
20 use List::Util; # for first
21 use List::MoreUtils; # for uniq and firstidx
22
23 # This is the priority loop. All supported strategies (exept Full house)
24 # are tried in turn in the sequence of their priorities, until one
25 # strategy is successful. The info about the found hit is returned as an
26 # anonymous array, which is then passed to module Found_info, which makes
27 # an object of it.
28 # Called from sub Run::_run_puzzle, the main loop of this program.
29 #
30 # At this step, strategy Full house (which has always highest priority) has
31 # already been tried. See sub full_house for details.
32
33 # Structure of the anonymous array returned by a successful strategy:
34 # Each element is a ref to an array with 4 elements
35 # 0: strategy name
36 # 1: action ('insert' or 'exclude')
37 # 2: ref to array of clues
38 # clues are unit objects, cell objects, candidate ids (in any sequence)
39 # clues are used by dialogs 'Show details' and 'History > Details'
40 # candidate ids have the stucture "cell name" . '-' . "cand digit"
41 # 3: ref to array of results
42 # for action 'insert': (value, cell object)
43 # for action 'exclude': each element has the structure
44 # $cell->Cell_num . '-' . "cand digit"
45 #
46
47 sub try_strategies {
48 # protect against problems
49 # on an excessive strategy scan after solving a puzzle
50 use List::Util qw(first);
51 # my @candcells = grep {! $_->Value} @cells[1 .. 81];
52 return unless grep {! $_->Value} @cells[1 .. 81];
53
54 foreach
55 my $strat_func ( @{ Games::Sudoku::Trainer::Priorities::strat_funcs_ref() } )
56 {
57 no strict 'refs';
58 my $found_ref = &$strat_func();
59 next unless $found_ref;
60
61 Games::Sudoku::Trainer::Found_info->new($found_ref);
62 return;
63 }
64 return;
65 }
66
67 sub _bivalue_universal_grave {
68 my @candcells = grep {! $_->Value} @cells[1 .. 81];
69 # protect against the confusing "not unique" message
70 # on an excessive strategy scan after solving a puzzle
71 return unless @candcells;
72
73 my $cand3cell;
74 foreach my $cell (@candcells) {
75 next unless $cell; # skip index 0
76 my $cell_cands = $cell->Candidates;
77 my $candcount = length($cell_cands);
78 return if $candcount > 3;
79 if ( $candcount == 3 ) {
80 return if $cand3cell; # more than 1 cell with 3 cand.s
81 $cand3cell = $cell;
82 }
83 }
84
85 $cand3cell or die "1\nThis sudoku puzzle is not unique\n";
86 my $cell_cands = $cand3cell->Candidates;
87 my @cand3 = split( '', $cell_cands );
88 foreach my $unit ( $cand3cell->get_Containers ) {
89 foreach my $cand (@cand3) {
90 if ( $unit->get_Cand_count($cand) == 3 ) {
91 my @clues = ( $unit, $cell_cands, $cand3cell );
92 my @result = ( $cand, $cand3cell );
93 return [ 'Bivalue Universal Grave',
94 'insert', \@clues, \@result ];
95 }
96 }
97 }
98 return;
99 } ## end sub _bivalue_universal_grave
100
101 sub _bli_and_lbi {
102 return _BLIandLBI('');
103 }
104
105 sub _block_line_interaction {
106 return _BLIandLBI('Block-Line Interaction');
107 }
108
109 # The working horse for strats 'Block-Line Interaction',
110 # 'Line-Block Interaction', and 'BLI and LBI'
111 # ($found_strat, $clues_ref, $exclude_ref) = _BLIandLBI($wanted_strat);
112 # $wanted_strat: 'Block-Line Interaction', 'Line-Block Interaction' or ''
113 # returns undef if $wanted_strat strategy given, but found the opposite
114 #
115 sub _BLIandLBI {
116 my $wanted = shift;
117
118 foreach my $block ( @blocks[ 1 .. 9 ] ) {
119 my @members = $block->get_Members;
120 my $cell1 = $members[0];
121 my $cell9 = $members[8];
122 my @crosslines = ( # all lines crossing this block
123 @rows[ $cell1->Row_num .. $cell9->Row_num ],
124 @cols[ $cell1->Col_num .. $cell9->Col_num ],
125 );
126 foreach my $line (@crosslines) {
127 my @cross = $block->crosssection($line); # the common cells
128 foreach my $digit ( 1 .. 9 ) {
129 my $block_cand = $block->get_Cand_count($digit);
130 next if $block_cand < 2;
131 my $line_cand = $line->get_Cand_count($digit);
132 next if $line_cand < 2;
133
134 # extract the cells with this digit
135 # as candidate in the cross section
136 my @have_cand = _cand_cells( $digit, @cross );
137 my $have_cand = @have_cand;
138 next if $have_cand < 2;
139 my ( $hit_unit, $strat );
140 next
141 unless (
142 $have_cand == $block_cand xor $have_cand == $line_cand );
143
144 # we found a BLI or LBI; is it the wanted type?
145 ( $hit_unit, $strat ) =
146 $have_cand == $block_cand
147 ? ( $line, 'Block-Line Interaction' )
148 : ( $block, 'Line-Block Interaction' );
149 next if ( $wanted and $strat ne $wanted ); # sorry
150
151 my @clues = ( $block, $line, $digit, @have_cand );
152 my $exclude_ref =
153 _excl_cands_exept( $hit_unit, $digit, @have_cand );
154 return [ $strat, 'exclude', \@clues, $exclude_ref ];
155 }
156 }
157 } ## end foreach...
158 return;
159 } ## end sub _BLIandLBI
160
161 # This is the only strategy that isn't called from the strategy loop
162 # (sub try_strategies). It is called from sub Run::_insert_presets and
163 # sub Trainer::_run_puzzle (the main loop of the Sudoku trainer).
164 # full_house($cell);
165 # $cell: The 3 container units of this cell are checked for full house
166 #
167 sub full_house {
168 my $cell = shift;
169
170 my %found_cells;
171 my $digit;
172
173 my @cell_containers = $cell->get_Containers;
174 foreach my $unit (@cell_containers) {
175 my @novalue_cells = $unit->active_Members;
176 next unless ( @novalue_cells == 1 );
177 my $novalue_cell = $novalue_cells[0];
178
179 # ignore if value already found for this cell (in a prev. unit)
180 next
181 if exists $found_cells{ $novalue_cell };
182 $found_cells{$novalue_cell}++;
183 $digit = $novalue_cell->Candidates;
184 $digit =~ /^[1-9]$/
185 or die "3\nNo candidate found in cell ", $novalue_cell->Name,
186 "\n ";
187 my @result = ( $digit, $novalue_cell );
188 my @clues = ( $unit, @result );
189 my $found_ref = [ 'Full House', 'insert', \@clues, \@result ];
190 my $found_obj = Games::Sudoku::Trainer::Found_info->new($found_ref);
191 }
192 return;
193 }
194
195 sub _hidden_pair {
196 foreach my $unit (@units) {
197
198 # collect all digits that are candidates in exactly 2 cells of this unit
199 my @cand2 = grep { $unit->get_Cand_count($_) == 2 } ( 1 .. 9 );
200 next if @cand2 < 2;
201
202 # collect the 2 cells for each of those digits
203 my @digit_info = map { [ $_, _cand_cells( $_, $unit, 2 ) ] } @cand2;
204
205 # Look for 2 of those cells that have the same digits
206 # No other digits are possible in this pair of cells
207 foreach my $idx1 ( 0 .. $#digit_info - 1 ) {
208 my $info1 = $digit_info[$idx1];
209 foreach my $idx2 ( $idx1 + 1 .. $#digit_info ) {
210 my $info2 = $digit_info[$idx2];
211 next
212 if ( $info1->[1] != $info2->[1]
213 or $info1->[2] != $info2->[2] );
214
215 # ignore if no candidates to exclude
216 next
217 if ( $info1->[1]->cands_count == 2
218 and $info1->[2]->cands_count == 2 );
219
220 # exclude all candidates of both cells except the 2 digits
221 my $ok_digits = $info1->[0] . $info2->[0];
222 my @exclude_info;
223 foreach my $idx ( 1, 2 ) {
224 my $cands = $info1->[$idx]->Candidates;
225
226 # ignore if no candidates to exclude in this cell
227 next
228 if length($cands) == 2;
229 $cands = _chars_p1_notin_p2( $cands, $ok_digits );
230 push( @exclude_info, $info1->[$idx]->Cell_num . "-$cands" );
231 }
232 my @clues = ( $unit, $ok_digits, $info1->[1], $info1->[2] );
233 return [ 'Hidden Pair', 'exclude', \@clues, \@exclude_info ];
234 }
235 }
236 } ## end foreach...
237 return;
238 } ## end sub _hidden_pair
239
240 sub _hidden_single {
241 foreach my $unit (@units) {
242 foreach my $digit ( 1 .. 9 ) {
243
244 # check for hidden single
245 next if ( $unit->get_Cand_count($digit) != 1 );
246
247 # find last cell in this unit that can hold this digit
248 my ($last_cell) = _cand_cells( $digit, $unit, 1 );
249 my @result = ( $digit, $last_cell );
250 my @clues = ( $unit, @result );
251 return [ 'Hidden Single', 'insert', \@clues, \@result ];
252 }
253 }
254 return;
255 }
256
257 sub _line_block_interaction {
258 return _BLIandLBI('Line-Block Interaction');
259 }
260
261 sub _naked_pair {
262 foreach my $unit (@units) {
263
264 # collect all cells in this unit that have exactly 2 candidates
265 my @all_pairs = _collect_2cands($unit);
266
267 # Look for 2 of those cells that have the same candidates
268 # These candidates can be excluded in all other cells
269 while ( $#all_pairs > 0 ) {
270 my ( $cell1, $cell1_2cands ) = @{ $all_pairs[0] };
271 foreach my $i ( 1 .. $#all_pairs ) {
272 my ( $cell2, $cell2_2cands ) = @{ $all_pairs[$i] };
273 next if ( $cell1_2cands != $cell2_2cands ); # cands differ
274 my $hitcands = $cell1_2cands;
275
276 # is there something to exclude in this unit?
277 next
278 if ( $unit->get_Cand_count( substr( $hitcands, 0, 1 ) ) == 2
279 and $unit->get_Cand_count( substr( $hitcands, 1, 1 ) ) ==
280 2 );
281
282 # Are both cells in the same block? If so, we can settle them
283 # here on the fly.
284 # Otherwise they would get caught later by one (sometimes two) LBIs.
285 my $unittype = ref $unit;
286 $unittype =~ s/.*::(\w+)$/$1/;
287 my $units_par = # units-parameter for sub _excl_cands_exept
288 ( $unittype ne 'Block'
289 and $cell1->Block_num == $cell2->Block_num )
290 ? [ $unit, $blocks[ $cell1->Block_num ] ]
291 : $unit;
292 my @clues = ( $unit, $hitcands, $cell1, $cell2 );
293 my $exclude_ref =
294 _excl_cands_exept( $units_par, $hitcands,
295 ( $cell1, $cell2 ) );
296 return [ 'Naked Pair', 'exclude', \@clues, $exclude_ref ];
297 }
298 shift @all_pairs;
299 }
300 } ## end foreach...
301 return;
302 } ## end sub _naked_pair
303
304 sub _naked_single {
305 foreach my $cell ( @cells[ 1 .. $#cells ] ) {
306 my $cell_cand = $cell->Candidates;
307 next if ( length($cell_cand) != 1 );
308 my @result = ( $cell_cand, $cell );
309 my @clues = @result;
310 return [ 'Naked Single', 'insert', \@clues, \@result ];
311 }
312 return;
313 }
314
315 sub _skyscraper {
316 my @line_infos;
317 foreach my $digit ( 1 .. 9 ) {
318
319 # collect all lines that have this digit as cand. in exactly 2 cells
320 my @cand2_lines = _map_filtered( "\$_->get_Cand_count($digit) == 2",
321 "[\$_, [_cand_cells( $digit, \$_, 2 )]]", @lines );
322 next if @cand2_lines < 2;
323
324 # for each of these lines add all infos that are needed
325 # to find a skyscraper
326 foreach my $cand_ref (@cand2_lines) {
327 my (%line_info);
328 $line_info{line} = $cand_ref->[0];
329 @line_info{qw/cella cellb/} = @{ $cand_ref->[1] };
330 $line_info{digit} = $digit;
331 my $linetype = ref $line_info{line};
332 $linetype =~ s/.*::(\w+)$/$1/;
333 # the index of the cell in the containing row or column
334 my $cell_idx = $linetype eq 'Row' ? 'Col_num' : 'Row_num';
335 @line_info{qw/posa posb/} =
336 map { $_->$cell_idx } ( @line_info{qw/cella cellb/} );
337 push @line_infos, \%line_info;
338 }
339 }
340
341 # search for 2 candidate lines that have exactly 1 of these cells
342 # in the same position
343 # these cells are the bottom cells of the skyscraper
344 # the others are the roof cells - find them
345 my ( %line1, %line2 );
346 while ( my $cand_ref1 = shift @line_infos ) {
347 %line1 = %$cand_ref1;
348 my $digit = $line1{digit};
349 foreach my $cand_ref2 (@line_infos) {
350 %line2 = %$cand_ref2;
351 next if ( $line2{digit} != $digit ); # need same digit
352 # need parallel lines
353 next if ( ref $line1{line} ne ref $line2{line} );
354
355 my $linetype = ref $line1{line};
356 $linetype =~ s/.*::(\w+)$/$1/;
357 # the index of the cell in the containing row or column
358 my $cell_idx = $linetype eq 'Row' ? 'Col_num' : 'Row_num';
359
360 use List::MoreUtils qw(uniq firstidx);
361 my @allpos = ( @line1{qw/posa posb/}, @line2{qw/posa posb/} );
362 my @uniqpos = uniq @allpos;
363 next if @uniqpos != 3;
364
365 # there are roof cells - find them
366 my @roof_pos = _chars_notcommon( "$line1{posa}$line1{posb}",
367 "$line2{posa}$line2{posb}" );
368 my %pos_cells;
369 @pos_cells{@allpos} =
370 ( @line1{qw/cella cellb/}, @line2{qw/cella cellb/} );
371 my @roof_cells = map { $pos_cells{$_} } @roof_pos;
372
373 # collect all common siblings of the roof cells
374 my @excl_cells = Games::Sudoku::Trainer::Cell->common_sibs(@roof_cells);
375 next unless @excl_cells; # no common siblings
376 # extract those siblings that have this digit as a cand.
377 my @have_cand = _cand_cells( $digit, @excl_cells );
378 next unless @have_cand; # sorry - no cand.s to exclude
379
380 my @clues = (
381 $line1{line}, $line2{line}, $digit, $line1{cella},
382 $line1{cellb}, $line2{cella}, $line2{cellb}
383 );
384 my @exclude_info =
385 map { $_->Cell_num . "-$digit" } @have_cand;
386 return [ 'Skyscraper', 'exclude', \@clues, \@exclude_info ];
387 } ## end foreach...
388 } ## end while...
389 return;
390 } ## end sub _skyscraper
391
392 sub _turbot_fish {
393 foreach my $digit ( 1 .. 9 ) {
394
395 # collect all lines that have this digit as candidate in exactly 2 cells
396 # my @cand2_lines =
397 # map {my @hit = _cand_cells( $digit, $_, 2 ); [$_, \@hit]}
398 # grep ({$_->get_Cand_count($digit) == 2} @lines);
399 my @cand2_lines = _map_filtered( "\$_->get_Cand_count($digit) == 2",
400 "[\$_, [_cand_cells( $digit, \$_, 2 )]]", @lines );
401
402 # get the cross lines through the hit cells
403 foreach my $cand_ref (@cand2_lines) {
404 my ( $line, $hit_cell_ref ) = @$cand_ref;
405
406 # the hit cells must be in different blocks
407 next
408 if ( $hit_cell_ref->[0]->Block_num ==
409 $hit_cell_ref->[1]->Block_num );
410
411 # get the cross lines through the hit cells
412 my ( $cross1, $cross2 ) =
413 map( { $line->crossline($_) } @$hit_cell_ref );
414
415 # investigate the cross lines
416 # both need at least 2 cells with this digit as candidate
417 # (this check is needed in case that
418 # Prio('Hidden Single') < Prio('Turbot Fish') )
419 next
420 if ( $cross1->get_Cand_count($digit) < 2
421 or $cross2->get_Cand_count($digit) < 2 );
422
423 my ( $chain_cell, $chain2_cell, $target_cell );
424 my @cross_cells;
425
426 TRYBOTH:
427 foreach my $swap ( 0, 1 ) {
428 if ($swap) {
429 ( $cross1, $cross2 ) = ( $cross2, $cross1 );
430 @$hit_cell_ref = reverse @$hit_cell_ref;
431 }
432 @cross_cells = _cand_cells( $digit, $cross1 );
433 my $hitblock = $hit_cell_ref->[0]->Block_num;
434 foreach my $cross_cell (@cross_cells) {
435 next if $cross_cell->Block_num == $hitblock;
436 my @block_cells =
437 _cand_cells( $digit, $blocks[ $cross_cell->Block_num ] );
438 next if @block_cells != 2;
439 $chain2_cell =
440 $block_cells[0] == $cross_cell
441 ? $block_cells[1]
442 : $block_cells[0];
443 my $unittype = ref $line;
444 $unittype =~ s/.*::(\w+)$/$1/;
445 $target_cell = $unittype eq 'Row'
446 ? Games::Sudoku::Trainer::Cell
447 ->by_pos( $chain2_cell->Row_num, $cross2->get_Index )
448 : Games::Sudoku::Trainer::Cell
449 ->by_pos( $cross2->get_Index, $chain2_cell->Col_num );
450 $chain_cell = $cross_cell;
451 last TRYBOTH if $target_cell->has_candidate($digit);
452 }
453 }
454 next unless $target_cell and $target_cell->has_candidate($digit);
455
456 my @clues = (
457 $line, $cross1, $digit, reverse(@$hit_cell_ref),
458 $chain_cell, $chain2_cell, $target_cell
459 );
460 my @exclude_info = $target_cell->Cell_num . "-$digit";
461 return [ 'Turbot Fish', 'exclude', \@clues, \@exclude_info ];
462 } ## end foreach...
463 } ## end foreach...
464 return;
465 } ## end sub _turbot_fish
466
467 sub _two_string_kite {
468 foreach my $digit ( 1 .. 9 ) {
469
470 # collect all rows that have this digit as candidate in exactly 2 cells
471 my @rows2 =
472 grep ( { $_ and $_->get_Cand_count($digit) == 2 } @rows );
473 next unless @rows2;
474
475 # collect all columns that have this digit as cand. in exactly 2 cells
476 my @cols2 =
477 grep ( { $_ and $_->get_Cand_count($digit) == 2 } @cols );
478 next unless @cols2;
479
480 # find a row and a column that have 1 of those cells in the same block
481 foreach my $row (@rows2) {
482 my @rowcells = _cand_cells( $digit, $row, 2 );
483 my @rowblocknums = map( { $_->Block_num } @rowcells );
484
485 # both cells of the row must be in different blocks
486 next if $rowblocknums[0] == $rowblocknums[1];
487 foreach my $col (@cols2) {
488 my @colcells = _cand_cells( $digit, $col, 2 );
489 my @colblocknums = map( { $_->Block_num } @colcells );
490
491 # both cells of the col must be in different blocks
492 next
493 if $colblocknums[0] == $colblocknums[1];
494 my $linecross = $row->crosssection($col);
495
496 # the lines may not cross at a candidate cell
497 next
498 if $linecross->has_candidate($digit);
499
500 my $crossblocknum = $linecross->Block_num;
501
502 # both lines must have one candidate cell in the cross block
503 next
504 if grep ( { ( $_->Block_num ) == $crossblocknum }
505 ( @rowcells, @colcells ) ) != 2;
506
507 # pick up the 2 cells outside the cross block.
508 # The lines through them cross at the crosscell.
509 my $rowcell =
510 $rowblocknums[0] == $crossblocknum
511 ? $rowcells[1]
512 : $rowcells[0];
513 my $colcell =
514 $colblocknums[0] == $crossblocknum
515 ? $colcells[1]
516 : $colcells[0];
517 my $crosscell =
518 Games::Sudoku::Trainer::Cell->by_pos( $colcell->Row_num,
519 $rowcell->Col_num );
520
521 # are there cand.s to exclude?
522 next
523 unless $crosscell->has_candidate($digit); # sorry
524
525 my @clues = ( $row, $col, $digit, @rowcells, @colcells );
526 return [
527 'Two-String Kite', 'exclude',
528 \@clues, [ $crosscell->Cell_num . "-$digit" ]
529 ];
530 } ## end foreach...
531 } ## end foreach...
532 } ## end foreach...
533 return;
534 } ## end sub _two_string_kite
535
536 sub _unique_rectangle_type_1 {
537 foreach my $row (@rows) {
538 next unless $row; # skip index 0
539 # collect all cells in this row that have exactly 2 candidates
540 my @all_pairs = _collect_2cands($row);
541
542 # Look for 2 of those cells that have the same candidates
543 while ( $#all_pairs > 0 ) {
544 my $pair1_ref = $all_pairs[0];
545 foreach my $i ( 1 .. $#all_pairs ) {
546 my $pair2_ref = $all_pairs[$i];
547 next if ( $pair1_ref->[1] != $pair2_ref->[1] ); # cands differ
548 # the 2 cand.s of the searched rect type 1
549 my $rectcands = $pair1_ref->[1];
550
551 # investigate the 2 columns that pass these cells
552 # both should have another cell with these candidates
553 # one of them should have another cell
554 # with exactly these candidates
555 my @pass_cols = map( { $row->crossline($_) }
556 ( $pair1_ref->[0], $pair2_ref->[0] ) );
557
558 my @passmembers = $pass_cols[0]->active_Members;
559 my @pass_pairs = map( {
560 my $cands = $_->Candidates;
561 my $hitcount =
562 _count_chars_p1_common_p2( $cands, $rectcands );
563 $hitcount > 1 ? $_ : ();
564 } @passmembers );
565 next if $#pass_pairs == 0; # another cell not found in 1st col
566
567 # look in the same row of the 2nd column for the 4th cell
568 # (because the 4 cells must form a rectangle)
569 my $cell3;
570 foreach my $cell (@pass_pairs) {
571 next if ( $cell == $pair1_ref->[0] );
572 $cell3 = $cell;
573 my $rownum = $cell3->Row_num();
574 my $cell4 = $pass_cols[1]->get_Member( $rownum - 1 );
575 my $cands = $cell4->Candidates;
576 my $hitcount =
577 _count_chars_p1_common_p2( $cands, $rectcands );
578 next if ( $hitcount < 2 ); # not both cand.s in 4th cell
579 next
580 unless (
581 length( $cell3->Candidates ) == 2 xor length($cands) ==
582 2 );
583
584 # found type 1
585 my @clues = (
586 $row, $pass_cols[0], $rectcands,
587 $pair1_ref->[0], $pair2_ref->[0], $cell3, $cell4
588 );
589 my $cell = length($cands) == 2 ? $cell3 : $cell4;
590 $cands = $cell->Candidates;
591
592 return [
593 'Unique Rectangle Type 1',
594 'exclude', \@clues, [ $cell->Cell_num . "-$rectcands" ]
595 ];
596 } ## end foreach...
597 } ## end foreach...
598 shift @all_pairs;
599 } ## end while...
600 } ## end foreach...
601 return;
602 } ## end sub _unique_rectangle_type_1
603
604 sub _unique_rectangle_type_2 {
605 foreach my $line (@lines) {
606
607 # collect all cells in this line that have exactly 2 candidates
608 my @all_pairs = _collect_2cands($line);
609
610 # Look for 2 of those cells that have the same candidates
611 while ( my $pair1_ref = shift @all_pairs ) {
612 foreach my $i ( 0 .. $#all_pairs ) {
613 my $pair2_ref = $all_pairs[$i];
614 next if ( $pair1_ref->[1] != $pair2_ref->[1] ); # cands differ
615
616 # investigate the 2 cross lines that pass these cells
617 # both should have another cell with these candidates
618 # plus one additional candidate
619 # both should have the same additional candidate
620 # $rectcands holds the 2 common candidates of the
621 # (searched) rectangle
622 my ( $cell1, $rectcands ) = @$pair1_ref;
623 my $cross1 = $line->crossline($cell1);
624 my @crossmembers = $cross1->active_Members;
625 my @crosspairs = map( {
626 my $cands = $_->Candidates;
627 my $hitcount =
628 _count_chars_p1_common_p2( $cands, $rectcands );
629 $hitcount == 2 && length($cands) == 3 ? $_ : ();
630 } @crossmembers );
631 next if $#crosspairs < 0; # another cell not found in 1st line
632
633 # for each possible 3rd cell compare with the corresp. 4th cell
634 foreach my $cell3 (@crosspairs) {
635 my $rownum = $cell3->Row_num();
636 my $cell2 = $pair2_ref->[0];
637 my $unittype = ref $line;
638 $unittype =~ s/.*::(\w+)$/$1/;
639 my $cell4 =
640 $unittype eq 'Row'
641 ? Games::Sudoku::Trainer::Cell->by_pos( $cell3->Row_num,
642 $cell2->Col_num )
643 : Games::Sudoku::Trainer::Cell->by_pos( $cell2->Row_num,
644 $cell3->Col_num );
645 next if $cell3->Candidates ne $cell4->Candidates;
646
647 # $exclcand gets the candidate to be excluded
648 my $exclcands = $cell3->Candidates;
649 $exclcands = _chars_p1_notin_p2( $exclcands, $rectcands );
650
651 my @clues = (
652 $line, $cross1, $rectcands, $cell1, $cell2,
653 $cell3, $cell4
654 );
655 my @cont3 = $cell3->get_Containers;
656 my @cont4 = $cell4->get_Containers;
657 my @common_units =
658 map { $cont3[$_] == $cont4[$_] ? $cont3[$_] : () } 0 .. 2;
659 my $exclude_ref =
660 _excl_cands_exept( \@common_units, $exclcands, $cell3,
661 $cell4 );
662 next unless @$exclude_ref;
663 return [ 'Unique Rectangle Type 2',
664 'exclude', \@clues, $exclude_ref ];
665 } ## end foreach...
666 } ## end foreach...
667 } ## end while...
668 } ## end foreach...
669 return;
670 } ## end sub _unique_rectangle_type_2
671
672 sub _x_wing {
673 foreach my $digit ( 1 .. 9 ) {
674 my ( $lineref, $cross_getter ) = ( \@rows, 'Col_num' );
675 foreach ( 1, 2 ) {
676 my @cand2_lines;
677
678 # collect all lines that have this digit as candidate
679 # in exactly 2 cells
680 @cand2_lines = _map_filtered( "\$_->get_Cand_count($digit) == 2",
681 "[\$_, _cand_cells( $digit, \$_, 2 )]", @$lineref );
682 next if @cand2_lines < 2;
683
684 # search for 2 candidate lines that have the 2 cells
685 # in the same position, thus forming a rectangle
686 while ( my $cand_ref1 = shift @cand2_lines ) {
687 my ( @hit_cells1, @hit_cells2 );
688 ( my $line1, @hit_cells1 ) = @$cand_ref1;
689 my @cross1 =
690 map( { $_->$cross_getter } @hit_cells1 )
691 ; # the indices of the cross lines
692 $lineref =
693 $cross_getter =~ /Row/
694 ? \@rows
695 : \@cols; # the type array of the cross lines (row or col)
696 foreach my $cand_ref2 (@cand2_lines) {
697 ( my $line2, @hit_cells2 ) = @$cand_ref2;
698 my @cross2 =
699 map( { $_->$cross_getter } @hit_cells2 )
700 ; # the indices of the cross lines
701 next
702 if ( $cross1[0] != $cross2[0]
703 or $cross1[1] != $cross2[1] ); # not the same crosslines
704
705 # we found an x-wing structure - are there cand.s to exclude in the cross lines?
706 next
707 if ( $lineref->[ $cross1[0] ]->get_Cand_count($digit) == 2
708 and $lineref->[ $cross1[1] ]->get_Cand_count($digit) ==
709 2 );
710
711 # sorry
712
713 my @clues =
714 ( $line1, $line2, $digit, @hit_cells1, @hit_cells2 );
715 my $exclude_ref =
716 _excl_cands_exept(
717 [ $lineref->[ $cross1[0] ], $lineref->[ $cross1[1] ] ],
718 $digit, @hit_cells1, @hit_cells2 );
719 return [ 'X Wing', 'exclude', \@clues, $exclude_ref ];
720 } ## end foreach...
721 } ## end while...
722 ( $lineref, $cross_getter ) = ( \@cols, 'Row_num' );
723 } ## end foreach...
724 } ## end foreach...
725 return;
726 } ## end sub _x_wing
727
728 sub _xy_wing {
729
730 # collect all cells that have exactly 2 candidates
731 my @all_pairs = _collect_2cands( @cells[ 1 .. 81 ] );
732
733 foreach my $i ( 0 .. $#all_pairs - 2 ) {
734 my ( $cell1, $cands1 ) = @{ $all_pairs[$i] };
735 foreach my $j ( $i + 1 .. $#all_pairs - 1 ) {
736 my ( $cell2, $cands2 ) = @{ $all_pairs[$j] };
737 ( my $match1 ) = ( $cands2 =~ /([$cands1]+)/ ) || '';
738 next unless length($match1) == 1; # not 1 common cand.
739 foreach my $k ( $j + 1 .. $#all_pairs ) {
740 my ( $cell3, $cands3 ) = @{ $all_pairs[$k] };
741 next if ( $cands3 eq $cands1 or $cands3 eq $cands2 );
742 my $nomatch =
743 _count_chars_p1_notin_p2( $cands3, $cands1 . $cands2 );
744 next if $nomatch > 0; # more than 3 cand.s total
745 my @chain = _chain_of( $cell1, $cell2, $cell3 );
746 next unless @chain;
747
748 my $excl = $chain[0]->Candidates;
749 my $keep = $chain[1]->Candidates;
750
751 # get the cand to be excluded
752 $excl = _chars_p1_notin_p2( $excl, $keep );
753 my @excl_cells =
754 Games::Sudoku::Trainer::Cell->common_sibs( $chain[0], $chain[2] );
755 next unless @excl_cells; # no common siblings
756 my @have_cand = _cand_cells( $excl, @excl_cells );
757 next unless @have_cand; # sorry - no cand to exclude
758
759 my @clues = ( @chain, "$keep$excl" );
760 my @exclude_info = map { $_->Cell_num . "-$excl" } @have_cand;
761 return [ 'XY Wing', 'exclude', \@clues, \@exclude_info ];
762 }
763 }
764 } ## end foreach...
765 return;
766 } ## end sub _xy_wing
767
768 # form a chain from all given cells
769 # support routine for sub _xy_wing
770 # @chain = _chain_of(list_of_unsorted_cells);
771 # returns undef on no success
772 #
773 sub _chain_of {
774 my @rand = @_;
775 my @chain;
776
777 push @chain, pop @rand;
778 my $last_link = $chain[-1]; # last chainlink found so far
779 my @lastconts = $last_link->get_Containers;
780 my $last_cont_idx = -1; # index (~ type) of last chaining container
781 my $first_cont_idx; # index (~ type) of 1st chaining container
782
783 while (@rand) {
784
785 # find next chainlink
786 my $currsize = @rand;
787 TRY_IDX:
788 for my $try_idx ( 0 .. $#rand )
789 { # we need the index on success for splice
790 my $cell = $rand[$try_idx];
791 my @newconts = $cell->get_Containers;
792
793 # if no success with the last chainlink, reverse the partial chain
794 for my $reversed ( 0, 1 ) {
795
796 # try chaining in all containers of the last chainlink
797
798 # must chain in different containers
799 foreach my $j ( 0 .. 2 ) {
800 next
801 if $j == $last_cont_idx;
802 next unless $newconts[$j] == $lastconts[$j];
803
804 # found chainlink
805 @chain == 1 and $first_cont_idx = $j;
806 @lastconts = @newconts;
807 $last_link = $cell;
808 $last_cont_idx = $j;
809 push @chain, $cell;
810 splice @rand, $try_idx, 1;
811 last TRY_IDX;
812 }
813 if ( $reversed or @chain == 1 )
814 { # cell doesn't fit here, try next
815 next TRY_IDX;
816 }
817
818 # reverse the partial chain to try connect to the
819 # currently 1st chainlink
820 @chain = reverse @chain;
821 $last_link = $chain[-1];
822 @lastconts = $last_link->get_Containers;
823 ( $first_cont_idx, $last_cont_idx ) =
824 ( $last_cont_idx, $first_cont_idx );
825 }
826 } ## end for...
827 return if $currsize == @rand; # broken chain
828 } ## end while...
829 return @chain;
830 } ## end sub _chain_of
831
832 #==============================================================================
833 #==============================================================================
834 # Exclude candidates from most cells in a unit or list of units
835 # _excl_cands_exept(unit-info, $exclcands, @cells_retain);
836 # unit-info: $unit or ref to list of units
837 # $exclcands: string of candidates to be excluded
838 # @cells_retain: list of cells that shall keep their candidates
839 # returns ref to list of cands to be excluded
840 # (format: cell-number . "-$exclcands")
841 #
842 sub _excl_cands_exept {
843 my ( $hit_unit, $exclcands, @have_cand ) = @_;
844 my @hit_units = ref $hit_unit eq 'ARRAY' ? @$hit_unit : ($hit_unit);
845
846 my @total_members; # all members of all units
847 my @cands = split( '', $exclcands );
848 foreach my $hit_unit (@hit_units) {
849 my @hit_cells = map { _cand_cells( $_, $hit_unit ) } @cands;
850
851 # all members with these cand. in the hit unit
852 my %all_members;
853 @all_members{@hit_cells} = (@hit_cells);
854
855 # keep the members in the cross section
856 delete @all_members{@have_cand};
857 push( @total_members, values %all_members );
858 }
859 my @exclude_info = map { $_->Cell_num . "-$exclcands" } @total_members;
860 return \@exclude_info;
861 }
862
863 # Extract all cells from the list that have this digit as a candidate
864 # @have_cand = _cand_cells($digit, @cell_list, $expect_count);
865 # ... = _cand_cells($digit, $unit, $expect_count);
866 # uses the members of the unit
867 # $expect_count: expected count of hit cells (optional)
868 # dies if expected count differs from actual count (code error)
869 #
870 sub _cand_cells {
871 my ( $digit, @cell_list ) = @_;
872
873 use File::Basename;
874
875 @cell_list or do {
876 my @trace = caller(0);
877 die "3\nProblem in file ", basename( $trace[1] ), " at line $trace[2]",
878 "\nNo cell list passed to sub _cand_cells\n";
879 };
880
881 my $expect_count = pop @cell_list unless ref $_[-1];
882 my $unit;
883 my @found;
884 if ( @cell_list == 1 and $cell_list[0]->isa('Games::Sudoku::Trainer::Unit') ) {
885 $unit = $cell_list[0];
886 @cell_list = @{ $unit->{Cand_cells}[$digit] };
887 @found = @cell_list;
888 }
889 else {
890 my $unittype = ref $cell_list[0];
891 $unittype =~ s/.*::(\w+)$/$1/;
892 $unittype eq 'Cell' or die "3\n$cell_list[0] must be a cell";
893 @found = grep { $_->has_candidate($digit) } @cell_list;
894 }
895
896 return @found if !defined $expect_count or @found == $expect_count;
897 my @trace = caller(0);
898 die "3\nProblem in file ", basename( $trace[1] ), " at line $trace[2]",
899 "\nExpected $expect_count cells with candidate $digit in ",
900 defined $unit ? 'unit ' . $unit->Name
901 : Games::Sudoku::Trainer::GUI::names(@cell_list),
902 ', found ', scalar @found, "\n";
903 }
904
905 # collect all cells from a list that have exactly 2 candidates
906 # my @all_twins = _collect_2cands(@cell_list);
907 # my @all_twins = _collect_2cands($unit); # uses the members of the unit
908 # returns list of refs to 2-element arrays:
909 # [cell-obj, string of the 2 cand.s in this cell
910 #
911 sub _collect_2cands {
912 my @cell_list = @_;
913 if ( @cell_list == 1 and $cell_list[0]->isa('Games::Sudoku::Trainer::Unit') ) {
914 @cell_list = $cell_list[0]->active_Members;
915 }
916
917 return _map_filtered( 'length($_->Candidates) == 2',
918 '[$_, $_->Candidates]', @cell_list );
919 }
920
921 # filter a list, then map to a new list and return this
922 # my @result =
923 # _map_filtered($filtercode_string, $mapcode_string, @sourcelist);
924 #
925 sub _map_filtered {
926 my ( $filter, $mapblock, @liste ) = @_;
927 @liste = grep { $_ } @liste; # skip index 0, if required (undef)
928 return () unless @liste;
929
930 my @res = eval "map {$mapblock} grep ({$filter} \@liste)";
931 # $@ and do {
932 if ($@) {
933 my $msg = " Filter: $filter\n Mapblock: $mapblock\n";
934 die "3\nEval error: $@$msg "; # final ' ' adds trace info
935 };
936 return @res;
937 }
938
939 #-----------------------------------------------------------------------
940 # Set operations on characters in strings
941 #-----------------------------------------------------------------------
942
943 # return all chars in $p1 that are not in $p2 (non-symmetric diff)
944 # $rest_p1 = _chars_p1_notin_p2($p1, $p2);
945 #
946 sub _chars_p1_notin_p2 {
947 my ( $p1, $p2 ) = @_;
948 $p1 =~ s/[$p2]//g; # remove common chars
949 return $p1;
950 }
951
952 # return count of chars in $p1 that are not in $p2 (non-symmetric diff)
953 # $count_excl = _count_chars_p1_notin_p2($p1, $p2);
954 #
955 sub _count_chars_p1_notin_p2 {
956 my ( $p1, $p2 ) = @_;
957 my $count_notin = $p1 =~ s/[^$p2]//g; # remove not common chars
958 return $count_notin;
959 }
960
961 # return all chars in $p1 that are also in $p2 (intersection)
962 # $common_chars = _chars_p1_common_p2($p1, $p2);
963 #
964 sub _chars_p1_common_p2 {
965 my ( $p1, $p2 ) = @_;
966 $p1 =~ s/[^$p2]//g; # remove not common chars
967 return $p1;
968 }
969
970 # return count of chars in $p1 that are also in $p2 (intersection)
971 # $count_common = _count_chars_p1_common_p2($p1, $p2);
972 #
973 sub _count_chars_p1_common_p2 {
974 my ( $p1, $p2 ) = @_;
975 my $count_common = $p1 =~ s/[$p2]//g; # remove common chars
976 return $count_common;
977 }
978
979 # return all chars that are not common (symmetric diff)
980 # ($rest_p1, $rest_p2) = _chars_p1_notin_p2($p1, $p2);
981 # Caution: Returns () if $p1 and $p2 have no common char
982 #
983 sub _chars_notcommon {
984 my ( $p1, $p2 ) = @_;
985 my $comm = $p1;
986 $comm =~ s/[^$p2]//g; # remove not common chars
987 return () unless $comm; # no common chars
988 $p1 =~ s/[$comm]//g; # remove common chars
989 $p2 =~ s/[$comm]//g; # remove common chars
990 return ( $p1, $p2 );
991 }
992
993 # return string of all chars found in given strings (union)
994 # $sorted_chars = _allchars{@strings};
995 #
996 sub _allchars {
997 my @strings = @_;
998 my %union;
999
1000 foreach my $string (@strings) {
1001 $union{$_} = undef foreach split '', $string;
1002 }
1003 return join '', sort keys %union;
1004 }
1005
1006 1;