Raku daily skill builders

Here is my Raku solution of the Task 1 on Week 65. The task is to print all $n-digit numbers, whose sum of digits is $s.

I never participated in the Perl Weekly Challenge but the recent tasks seem to be quite appealing to solve them with Raku. Maybe I will go backwards to the previous weeks to seek for more pearls there.

Here is my Raku solution of the Task 1 on Week 65. The task is to print all $n-digit numbers, whose sum of digits is $s.

The original task have these numbers as a starting point:

my $n = 2;
my $s = 4;

First, let us generate a sequence of all 2-digit numbers. They are, obviously, these:

my @range = 10**($n - 1) ..^ 10**$n;
say @range;
# [10 11 12 13 14 . . . 97 98 99]

Second, filter the numbers that we need. To get the sum of digits in a number, split it and apply the + operation via the reduction operator:

my @required = @range.grep({$s == [+] $_.comb});
say @required;
# [13 22 31 40]

Finally, assemble the parts of the solution together:

put (10**($n - 1) ..^ 10**$n).grep({$s == [+] $_.comb});
# 13 22 31 40

I am using put here to get cleaner output comparing to what say would print.

Modify the initial conditions to get other sequences, for example:

my $n = 3;
my $s = 14;

# 149 158 167 176 185 194 . . . 923 932 941 950

The final code is on GitHub.

Navigation to the Raku challenges post series

One thought on “Raku daily skill builders”

Leave a Reply

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

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code