Let us create a one-liner to generate the sequence of the so-called Gray code in the Raku programming language.
This code is essentially a method of binary coding so that for each of the following integer number, you only change a single bit.
So, for example, the 2-bit sequence (which, as a regular binary representation, can host 4 different values) is 00, 01, 11, 10.
Or, in decimal view: 0, 1, 3, 2
.
In a traditional binary representation, you have to set all lower bits to zero every time you cross the power of two, as in 0111
→ 1000
. If you work with a row of electromechanical relay, you get much stronger noise in this case.
There are a few ways to generate a sequence, let me take the most efficient one, which you can encode in a single line in Raku:
put map {$_ +^ ($_ div 2)}, ^2**@*ARGS[0];
To use the program, pass the number of bits as a command-line argument. For example:
$ raku gray.raku 4 0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8
→ GitHub repository
→ Navigation to the Raku challenges post series