How to resolve the algorithm Generate random chess position step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Generate random chess position step by step in the Raku programming language

Table of Contents

Problem Statement

Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced,  but it must comply to the following rules:

No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Generate random chess position step by step in the Raku programming language

Source code in the raku programming language

sub pick-FEN {
    # First we chose how many pieces to place
    my $n = (2..32).pick;

    # Then we pick $n squares
    my @n = (^64).pick($n);

    # We try to find suitable king positions on non-adjacent squares.
    # If we could not find any, we return recursively
    return pick-FEN() unless
    my @kings[2] = first -> [$a, $b] {
        $a !== $b && abs($a div 8 - $b div 8) | abs($a mod 8 - $b mod 8) > 1
    }, (@n X @n);

    # We make a list of pieces we can pick (apart from the kings)
    my @pieces = 

; # We make a list of two king symbols to pick randomly a black or white king my @k = .pick(*); return (gather for ^64 -> $sq { if $sq == @kings.any { take @k.shift } elsif $sq == @n.any { my $row = 7 - $sq div 8; take $row == 7 ?? @pieces.grep(none('P')).pick !! $row == 0 ?? @pieces.grep(none('p')).pick !! @pieces.pick; } else { take 'ø' } }).rotor(8)».join».subst(/ø+/,{ .chars }, :g).join('/') ~ ' w - - 0 1'; } say pick-FEN();


You may also check:How to resolve the algorithm Long multiplication step by step in the Fortran programming language
You may also check:How to resolve the algorithm User input/Text step by step in the jq programming language
You may also check:How to resolve the algorithm Calkin-Wilf sequence step by step in the jq programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the Rust programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Slate programming language