Peaceful chess queen armies: Difference between revisions

m
→‎Verbose: more efficient, return 1st result found
(→‎{{header|Perl}}: Added refactored version of code)
m (→‎Verbose: more efficient, return 1st result found)
Line 1,759:
W---W</pre>
===Verbose===
A refactored version of the same code, with fancier output. Does not scale well for larger boards.
<lang perl>use strict;
use warnings;
Line 1,772:
sub place {
my($board, $n, $m, $empty_square) = @_;
state (%seen,$attack);
 
# logic of 'attack' regex: queen ( ... paths between queens containing only empty squares ... ) queen of other color
myunless ($attack) ={
$attack =
'([WB])' . # 1st queen
'(?:[WB])' . # 1st queen
join('|(?:', .
"[$empty_square]*"join('|',
map { "[$empty_square]*",
"(?^s:.map {$_}(?:[$empty_square].{$_})*)"
} $n-1, $n, "(?^s:.{$n+1_}(?:[$empty_square].{$_})*)"
) . } $n-1, $n, $n+1
' )' .
'(?!\1)[WB]'; # 2nd')' queen.
'(?!\1)[WB])' . ; # 1st2nd queen
}
 
# bail out if seen this configuration previously, or attack detected
Line 1,791 ⟶ 1,793:
 
# success if queen count is m×2
$solution = $board and returngoto DONE if $m * 2 == (my $have = $board =~ tr/WB//);
 
# place the next queen (alternating colors each time)
Line 1,804 ⟶ 1,806:
place( $board, $n, $m, $empty_square );
 
DONE: say $solution
? sprintf "Solution to $m $n\n\n%s", map { s/(.)/$1 /gm; s/B /♛/gm; s/W /♕/gmr } $solution
: "No solution to $m $n";</lang>
Line 1,810 ⟶ 1,812:
<pre>Solution to 4 5
 
♕◦ • ◦ ♕◦
♛• ◦ • ♛•
• ♛• ♛•
♛• ◦ • ♛•
♕◦ • ◦ ♕◦</pre>
♛• ◦ • ◦
• ◦ ♕◦ ♕
</pre>
 
=={{header|Phix}}==
2,392

edits