Weekly Challenge 091

Simon Green - Dec 14 '20 - - Dev Community

Challenge 091

TASK #1 › Count Number

Task

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.

Examples

» ./ch-1.pl 1122234
21321314

» ./ch-1.pl 2333445
12332415

» ./ch-1.pl 12345
1112131415
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Jump Game

Task

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.

Examples

» ./ch-2.pl 1 2 1 2
1

» ./ch-2.pl 2 1 1 0 2
0
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .