ETOOBUSY 🚀 minimal blogging for the impatient
PWC091 - Jump Game
TL;DR
On with TASK #2 from the Perl Weekly Challenge #091. Enjoy!
The challenge
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.
The questions
The challenge is pretty clear, apart from a detail… is @N
really
composed of positive numbers only? That 0
in the second example looks a
bit out of place 🧐
The solution
Here we go:
sub jump_game ($N) {
my $position = 0;
$position += $N->[$position] while $position < $#$N && $N->[$position];
return $position == $#$N ? 1 : 0;
}
Here, it’s really just a matter of following the crumbs. We start with our
$position
tracker at index 0
, then advance it according to the contents
of the array, taking a few cares:
- if the index goes exactly on the last spot or beyond, it’s time to stop;
- if the jump length is
0
we stop as well… and avoid an infinite loop!
After the loop terminates, it’s a matter of figuring if we landed to the last position or not.
Have a good one!