Move Until Obstacle: Array Manipulation in Action

Introduction

Welcome! In this lesson, we’ll tackle an engaging problem that involves array traversal and looping in Ruby. Imagine you’re designing a simple game where a player moves along a linear array, and their progress depends on the values they encounter. Along the way, they may hit an obstacle that stops them.

This task is a perfect opportunity to practice working with arrays and implementing logical flow using loops. Let’s dive into it!

Task Statement

The task is to implement a function called navigate_array(numbers, obstacle). Here’s how it works:

  • You are given an array of integers, numbers, and an integer obstacle.
  • Starting at the 0th index of the array, the value at each position indicates the number of steps the player can move forward.
  • The goal is to move as far as possible without landing on a position where the value equals obstacle. If the player encounters an obstacle, return the index of that position.
  • If the player navigates the array without encountering an obstacle, return the total number of moves they made.

For example:

  1. If numbers = [2, 3, 3, 4, 2, 4] and obstacle = 4, the function should return 5. The player moves to indices 2 and 5 but encounters the obstacle 4 at index 5.
  2. If numbers = [4, 1, 2, 2, 4, 2, 2] and obstacle = 2, the function should return 2, as the player exits the array after 2 moves.

Let’s break this problem into manageable steps.

Step 1: Initialize Variables

First, define variables to track the player’s current position (position) and the number of moves they’ve made (moves). Both should start at 0.

def navigate_array(numbers, obstacle)
  position = 0
  moves = 0

These variables will help us monitor the player’s progress as they move through the array.

Step 2: Traverse the Array

We'll use a loop do construct in place of a traditional while loop to traverse the array. The loop will persist until explicitly broken.

  loop do

This loop construct gives flexibility in deciding when to break out based on specific conditions inside the loop.

Step 3: Check for Obstacles

Within the loop, first check if the current position exceeds or meets the array's length. If so, terminate the loop using break. Then, check if the current position holds the obstacle. If it does, return the current position.

    return position if numbers[position] == obstacle
    break if position >= numbers.length

This segment ensures that the player stops when encountering an obstacle or reaching array boundaries.

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