Move Until Obstacle Game with Slice Manipulation in Go
Introduction
Welcome! Today's lesson involves an exciting task that blends basic operations with slice manipulation in Go. We'll be implementing a game called "Move Until Obstacle" using an integer slice. Picture yourself as a game developer, and get ready to dive into the captivating world of problem-solving with Go!
Task Statement
In the "Move Until Obstacle" game, the player begins at the start of a linear slice of integers. The number at each position in the slice indicates how many steps a player can move to the right. An obstacle number is a position in the slice where the player cannot land. The objective is to move as far to the right as possible until the player either encounters an obstacle or reaches the end of the slice.
Your function, func solution(numbers []int, obstacle int) int, should calculate and return the number of moves needed to reach the end of the slice without encountering an obstacle. If the player encounters an obstacle, the function should return the index where this obstacle is found.
For example, if the function receives the input: numbers := []int{2, 3, 3, 4, 2, 4} and obstacle := 4, it should return 5. This is because the player starts on 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 as inputs numbers := []int{4, 1, 2, 2, 4, 2, 2} and obstacle := 2, the output should be 2. 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 2.
Step 1 - Initialization
The first step is to ensure we have variables to track the player's position and the moves they've made. We'll initialize position and moves to 0 using Go's := syntax:
Step 2 - Main Loop
We'll use a for loop to iterate over the slice, continuing as long as position is less than the length of the slice, which we access with len(numbers):
