Generate Chess960 starting position: Difference between revisions

→‎{{header|Raku}}: Add from-spid option.
(Added 11l)
(→‎{{header|Raku}}: Add from-spid option.)
Line 1,586:
♜♚♝♜♞♛♞♝</pre>
If you run this you'll see that most of the time is spent in compilation, so in the case of separate precompilation the table of 960 entries merely needs to be deserialized back into memory. Picking from those entries guarantees uniform distribution over all possible boards.
 
<big><big><big><big><pre>♛♝♜♚♝♞♞♜</pre></big></big></big></big>
=== From Starting Position ID Number (SPID) ===
There is a [https://en.wikipedia.org/wiki/Fischer_random_chess_numbering_scheme standard numbering scheme] for Chess960 positions, assigning each an index in the range 0..959. This function will generate the corresponding position from a given index number (or fall back to a random one if no index is specified, making it yet another solution to the general problem).
 
<lang perl6>subset Pos960 of Int where { $_ ~~ ^960 };
sub chess960(Pos960 $position = (^960).pick) {
 
# We remember the remainder used to place first bishop in order to place the
# second
my $b1;
# And likewise remember the chosen combination for knights between those
# placements
my @n;
# Piece symbols and positioning rules in order. Start with the position
# number. At each step, divide by the divisor; the quotient becomes the
# dividend for the next step. Feed the remainder into the specified code block
# to get a space number N, then place the piece in the Nth empty space left in
# the array.
my @rules = (
#divisor, mapping function, piece
( 4, { $b1 = $_; 2 * $_ + 1 }, '♝' ),
( 4, { 2 * $_ - ($_ > $b1 ?? 1 !! 0) }, '♝' ),
( 6, { $_ }, '♛' ),
(10, { @n = combinations(5,2)[$_]; @n[0] }, '♞' ),
( 1, { @n[1]-1 }, '♞' ),
( 1, { 0 }, '♜' ),
( 1, { 0 }, '♚' ),
( 1, { 0 }, '♜' )
);
# Initial array, using '-' to represent empty spaces
my @array = «-» xx 8;
# Working value that starts as the position number but is divided by the
# divisor at each placement step.
my $p = $position;
# Loop over the placement rules
for @rules -> ($divisor, $block, $piece) {
# get remainder when divided by divisor
(my $remainder, $p) = $p.polymod($divisor);
# apply mapping function
my $space = $block($remainder);
# find index of the $space'th element of the array that's still empty
my $index = @array.kv.grep(-> $i,$v { $v eq '-' })[$space][0];
# and place the piece
@array[$index] = $piece;
}
return @array;
}</lang>
 
=={{header|REXX}}==
1,479

edits