Raku challenge Week 69, issue 1

The task is to find all so-called strobogrammatic numbers, which are the numbers that look the same if you rotate them upside down.

This morning, a new Perl Weekly Challenge arrived, so here are the solutions in the Raku programming language.

This week, both tasks are great for illustrating the features of Raku. Let me start with the first task.

The task is to find the so-called strobogrammatic numbers, which are the numbers that look the same if you rotate them upside down.

A classical example of such numbers is 69. It is a bit vaguely defined which numbers we can consider acceptable. If there is no question about 0, 6, 8, and 9, there are some doubts about 1. It’s upside-down version does not look the same in many fonts. Well, actually, 8 is also not trully symmetrical vertically. But all these choices are up to you and can be easily tuned in the program. The definition on Wikipedia includes 0, 1, 6, 8, and 9.

Here is my solution:

my $a = 0;
my $b = 2000;

put grep {
        $_ ~~ / ^ <[01689]>+ $ / &&
        $_ eq $_.trans('69' => '96').flip
    },
    $a..$b;

The range $a..$b is filtered with a combined condition:

First, a number can only contain the allowed digits:

$_ ~~ / ^ <[01689]>+ $ /

Second, its upside-down copy must be the same number:

$_ eq $_.trans('69' => '96').flip

In the second condition, 6s and 9s are swapped. There is no need to swap the other digits, as they keep representing themselves after reversing the string.

Notice that this solution indirectly treats each numbers from the range as a string.

For the input values 0 and 200, the program prints:

$ raku ch-1.raku
0 1 8 11 69 88 96 101 111 181

GitHub repository
Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *