Raku challenge week 72

Raku challenge, week 72. Task 1: count trailing zeroes in a factorial of an integer. Task 2: Get lines A to B from a text file.

This week, two simple tasks were offered for our entertainment.

[ez-toc]

Count trailing zeros

The task is to count trailing zeros in a factorial of a given integer number.

Computing factorials is my favourite task in Raku, and it is an extremely simple task:

my $f = [*] 1..$n;

Counting zeroes at the end of the string is a bit trickier:

say ($f ~~ / 0+ $/ // '').chars;

The number is treated as a string here, and if there are trailing zeroes, they will be taken to a Match object, which you can then implicitly convert to a string and take its length. If there are no zeros, we take an empty string instead.

So, the whole program is here:

unit sub MAIN(Int $n);

my $f = [*] 1..$n;
say "$n! = $f";
say ($f ~~ / 0+ $/ // '').chars;

Run it to see how it works:

$ raku ch-1.raku 10
10! = 3628800
2

Line range

The second task is to take a text file input.txt and print the lines between A and B, where A and B are integers corresponding the existing line numbers in the file.

Well, this task is rather simple, and can be done as a one-liner:

unit sub MAIN(Int $a, Int $b where 0 < $a <= $b <= 100);

.say for 'input.txt'.IO.lines[$a-1 ..^ $b];

If the file is small enough, you don’t have to worry about the efficiency of the program. For bigger files, probably, too, as lines returns a Supply, and I hope that it is lazy, so the program will not take the whole file in memory before you can read its first lines.

→ GitHub repository
→ Navigation to the Raku challenges post series

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