Implementing a "Move Until Obstacle" Game

Introduction

Welcome! This lesson involves an engaging task that combines basic operations with array manipulation. We will implement a "Move Until Obstacle" game using an integer array in TypeScript. Visualize yourself as a game developer and get ready to immerse yourself in the fascinating world of problem-solving with enhanced type safety!

Task Statement

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 on 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 moveUntilObstacle(numbers: number[], obstacle: number): number, 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 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.

Solution Building: Step 1

Our first step is to ensure we have variables to track the player, i.e., their current position and the moves they've made so far. We'll name them position and moves, initializing both to 0 with explicit type annotations for clarity:

function moveUntilObstacle(numbers: number[], obstacle: number): number {
    let position: number = 0;
    let moves: number = 0;

Solution Building: Step 2 - Main Loop

Next, we'll use a while loop to iterate over the array. It continues as long as position is less than the size of the array numbers, which we get using numbers.length:

function moveUntilObstacle(numbers: number[], obstacle: number): number {
    let position: number = 0;
    let moves: number = 0;
    while (position < numbers.length) {
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal