Dominoes: Difference between revisions

m
(→‎{{header|Perl}}: eliminate use of globals, no 'eval', any size grid, added extra credit)
m (→‎{{header|Perl}}: rearrange)
Line 323:
{{libheader|ntheory}}
<syntaxhighlight lang="perl">use v5.36;
 
sub find ($rows, $cols, $x, $y, $try, $orig) {
state $solution;
my $sum = $rows + $cols;
my $gap = qr/(.{$sum}) (.{$sum})/s;
 
if( $x > $y ) {
$x = 0;
$solution = $orig |. $try and return if ++$y == $rows; # solved!
}
 
while ( $try =~ /(?=(?|$x $gap $y|$y $gap $x))/gx ) { # vertical
my $new = $try;
substr $new, $-[0], 2*($rows+$cols)+3, " $1+$2 ";
find($rows, $cols, $x + 1, $y, $new, $orig );
}
 
while ( $try =~ /(?=$x $y|$y $x)/g ) { # horizontal
my $new = $try;
substr $new, $-[0], 3, ' + ';
find($rows, $cols, $x + 1, $y, $new, $orig );
}
 
$solution
 
# NB: not 'blank' lines, need to be full-width white-space
Line 389 ⟶ 364:
1 2 0 1
END
 
sub find ($rows, $cols, $x, $y, $try, $orig) {
state $solution;
my $sum = $rows + $cols;
my $gap = qr/(.{$sum}) (.{$sum})/s;
 
if( $x > $y ) {
$x = 0;
$solution = $orig |. $try and return if ++$y == $rows; # solved!
}
 
while ( $try =~ /(?=(?|$x $gap $y|$y $gap $x))/gx ) { # vertical
my $new = $try;
substr $new, $-[0], 2*($rows+$cols)+3, " $1+$2 ";
find($rows, $cols, $x + 1, $y, $new, $orig );
}
 
while ( $try =~ /(?=$x $y|$y $x)/g ) { # horizontal
my $new = $try;
substr $new, $-[0], 3, ' + ';
find($rows, $cols, $x + 1, $y, $new, $orig );
}
 
$solution
 
say find(7, 8, 0, 0, $grid1, $grid1 ) . "\n=======\n\n";
2,392

edits