Welcome! This lesson involves a thrilling task that combines basic operations with array manipulation in JavaScript. We will be implementing a "Move Until Obstacle" game using an integer array. Visualize yourself as a game developer, and get ready to delve into the exciting world of problem-solving!
In the "Move Until Obstacle" game, the player begins at the start of a linear array of integers. The number at each position indicates how many steps a player can move to the right. An obstacle number is one upon which the player cannot land. The goal is to move as far to the right as possible until either an obstacle stops the player or the player reaches the end of the array.
Your function, function solution(numbers, obstacle)
, should tally and return the number of moves needed to reach the end of the array without encountering an obstacle. If the player encounters an obstacle, the function should return the index at which this obstacle lies.
For example, if the function receives the input: numbers = [2, 3, 3, 4, 2, 4]
and obstacle = 4
, it should return 5
. This is because the player starts at the 0th index, takes 2 steps as indicated by the number at the 0th index (landing on the 2nd index), and then takes 3 more steps, as indicated by the number at the 2nd index, to land on the 5th index, which is the obstacle 4
.
If the function receives the following input: numbers = [4, 1, 2, 2, 4, 2, 2]
and obstacle = 2
, the output should be . The player starts at the 0th index, takes 4 steps, lands on the 4th index, then takes 4 more steps, which brings the player outside the array. So the total number of steps the player takes is .
