Generate Chess960 starting position
First, using a list with three rooks and no king, we keep generating a random piece order until the two bishops are on opposite colors. Then we sneakily promote the second of the three rooks to a king.
repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join }
s:2nd['♖'] = '♔';
say .comb;Output:
♕ ♗ ♖ ♘ ♔ ♖ ♗ ♘Here's a more "functional" solution that avoids side effects
sub chess960 {
.subst(:nth(2), /'♜'/, '♚') given
first rx/ '♝' [..]* '♝' /,
< ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.pick(*).join xx *;
}
say chess960;Output:
♛♝♜♚♝♞♞♜We can also pregenerate the list of 960 positions, though the method we use below is a bit wasteful, since it generates 40320 candidates only to throw most of them away. This is essentially the same filtering algorithm but written in the form of a list comprehension rather than nested map and grep. (The list comprehension is actually faster currently.) Note that the constant is calculated at compile time, because, well, it's a constant. Just a big fancy one.
constant chess960 =
< ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚');
.say for chess960;Here's a much faster way (about 30x) to generate all 960 variants by construction. No need to filter for uniqueness, since it produces exactly 960 entries.
Output:
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.
Raku: Generate from SP-ID
There is a 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).
Output:
Last updated
Was this helpful?