DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 091

Challenge 091

TASK #1 › Count Number


You are given a positive number $N.

Write a script to count number and display as you read it.

My solution

The task mentions a positive number (as opposed to a positive integer), but didn't give an example of what to do with a dot, so my script will only accept integers.

This is one of those tasks where I'm interested in how other Team PWC members attempt it. I'm sure there is a way to do this purely with a regular expression, but after about 10 minutes of trying to find the correct syntax, I abandoned that idea.

In the end I went with something that just works™. I take the first character, and then use a regular expression pattern /^($char+)(.*)$/ to remove the one or more occurrences of that character. I continue until the string is empty.

Then it is simply a matter of displaying the new number made up of the length and the number for each match.


» ./ 1122234

» ./ 2333445

» ./ 12345
Enter fullscreen mode Exit fullscreen mode

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.

My solution

Like with the first task it is suggested that any positive number is valid. However zero - which is not a positive number - is used in an example. It also doesn't make sense to have a fractional number, as you can't jump in non whole numbers. So for this task, I only allow non-negative integers.

For this tasks, I have a value $position which records my current position.

  • I return 1 if the current position is the last index (array length - 1). In this case we have landed on the last index.
  • If the current position is greater than the last index I return 0. We have overshot the last index, and therefore no solution is possible.
  • I also return 0 if the value at the current position is 0. In this case we will have an endless loop that will never move forward.
  • I then increase the $position variable by the value of the current index, and repeat the above tests.


» ./ 1 2 1 2

» ./ 2 1 1 0 2
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

simongreennet profile image
Simon Green

And without failure, the first Perl pull request (by Neil) has the solution to the first task using just a regular expression. As always, I never look at other people's solutions until after I have submitted my own.

My failure was I was trying to use \1 for the inner match when I actually wanted \2 #TIL