Hi, here’s my Raku breakfast with the solutions of Week 91 of The Weekly Challenge.
Task 1. Count Number
You are given a positive number $N
. Write a script to count the number of digits and display as you read it.
Example:
Input: $N = 1122234
Output: 21321314
as we read "two 1 three 2 one 3 one 4"
OK, so we actually don’t have to spell the number of repetitions as I originally thought (and solved 🙂 ) but we just need to print the number as a digit (yes, I think we are OK to not go beyond 9 repetitions of a digit).
And so, here’s the whole program:
unit sub MAIN(Int $n = 1122234); print .Str.chars ~ .[0] for $n ~~ m:g/ (\d) $0* /; say '';
Maybe we even can gain the line by replacing $n
with @*ARGS[0]
, but you also may think of how to get rid of the last line that makes the output cleaner.
In the regex, I match a single digit (\d)
and then try to find more copies of it: $0*
. As there’s a :g
adverb, the regex will be applied as many times as needed to cover the whole input.
Inside the main loop, there’s an interesting case: we have a Match object as the topic variable, and I am calling .Str.chars
and .[0]
on it. This is probably the best illustration of when you explicitly call subscripting brackets as a method.
Here is the output for a couple of inputs:
$ raku ch-1.raku 21321314 $ raku ch-1.raku 12333345556 111243143516<
Update
After I looked at Stuart Little’s solution, I realised that I forgot about map
existence again. So, here’s an updated solution that eliminates the problem with printing the final newline:
unit sub MAIN(Int $n = 1122234); ($n ~~ m:g/ (\d) $0* /).map({.Str.chars ~ .[0]}).join.say;<
Task 2. Jump Game
You are given an array of positive numbers @N
, where value at each index determines how far you are allowed to jump further. Write a script to decide if you can jump to the last index. Print 1 if you are able to reach the last index otherwise 0.
Example:
Input: @N = (1, 2, 1, 2)
Output: 1
as we jump one place from index 0 and then twoe places from index 1 to reach the last index.
Right, so the input array is actually a list of instructions that moves us over the same instruction list :-).
So, here’s my solution:
unit sub MAIN(*@a); my $pos = 0; $pos += @a[$pos] while @a[$pos] && $pos < @a.end; say $pos == @a.end ?? 1 !! 0;
In the loop, I am moving by the given number of steps towards the end of the data. An important thing is that you have to control not only that the position does not go outside of the array, but also that the current value is not zero (otherwise, you enter an infinite loop).
A couple of test runs for your pleasure:
$ raku ch-2.raku 1 2 1 2 1 $ raku ch-2.raku 2 1 1 0 2 0
* * *
→ GitHub repository
→ Navigation to the Raku challenges post series
One thought on “Raku Challenge Week 91”