Raku challenge Week 26

Hello, let us solve the text-processing Task 1 from the Week 26 of the Perl Weekly Challenge. The task is: Take the two words and count all letters in the second word, which are present in the first word.

I have two solutions here, and I believe there is potential to make them shorter.

Hello, let us solve the text-processing Task 1 from Week 26 of the Perl Weekly Challenge. The task, after deciphering the original phrasing, is:

Take the two words and count all letters in the second word, which are present in the first word.

I have two solutions here, and I believe there is potential to make them shorter.

1

In the first solution, a set $alphabet is created out of the letters from the first word $pattern. Then you also split the second word into letters ($test.comb ) and filter that list so that only the letters from the $alphabet can escape. And print the number of such cases (.elems).

my ($pattern, $test) = @*ARGS;

my $alphabet = set($pattern.comb);
say $test.comb.grep({$alphabet{$_}:exists}).elems;

Run the program and pass two words to it:

$ raku ch-1.raku chancellor chocolate
8

2

In my second solution, no separate alphabet is needed; we scan the letters in the second word (for $test.comb) and try to find them in the first word ($pattern.match($_)). If it is found, then (&&) the counter is incremented: $count++.

my ($pattern, $test) = @*ARGS;

my $count = 0;
$pattern.match($_) && $count++ for $test.comb;
say $count;

This program has the same interface as the previous one:

$ raku ch-1a.raku chancellor chocolate
8

3

And when you have the program completed, you understand that you can merge them to get a proper concise one-line solution!

my ($pattern, $test) = @*ARGS;

say $test.comb.grep({$pattern.match($_)}).elems;

And that’s all for now.

GitHub repository
Navigation to the Raku challenges post series

Leave a Reply

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