Introduction

Welcome to a delightful lesson on array traversal! Today, we invite you to join an endearing bunny named Gloria on an intricate quest. Gloria has a soft spot for number games, especially when they involve hopping between arrays.

Our goal on this exciting journey is to assist Gloria through her escapade and identify the maximum value she encounters along the way. Are you ready to embark on this adventure?

Task Statement

Gloria’s journey involves two arrays, arrayA and arrayB, filled with non-negative integers. She starts at the first element of arrayA and uses its value as an index to hop to arrayB. From there, the value in arrayB determines her next hop back to arrayA. Gloria continues hopping until she finds herself back at the starting position in arrayA.

Your task is to implement a Ruby method, max_value_from_hops(arrayA, arrayB), that calculates and returns the highest value Gloria encounters in arrayB during her journey.

For example, consider:

arrayA = [2, 4, 3, 1, 6]
arrayB = [4, 0, 3, 2, 0]

The method should return 3. Gloria’s journey would proceed as follows:

  1. Start at arrayA[0] (value 2).
  2. Hop to arrayB[2] (value 3).
  3. Hop to arrayA[3] (value 1).
  4. Hop to arrayB[1] (value 0).
  5. Return to arrayA[0], completing her journey.

The highest value Gloria encounters in arrayB is 3.

Step 1 - Initializing Values

Before Gloria sets out on her hopping adventure, we must initialize:

  • indexA to track her current position in arrayA.
  • max_value to store the highest value she encounters during the journey.
def max_value_from_hops(arrayA, arrayB)
  indexA = 0                  # Gloria starts at the first position in arrayA
  max_value = 0               # Initialize max_value to zero

These variables are Gloria’s essential tools for navigating her journey and recording her discoveries.

Step 2 - The Main Loop

To guide Gloria through her journey:

  1. Use the value at arrayA[indexA] as an index to hop to arrayB.
  2. Update max_value if Gloria finds a new highest value in arrayB.
  3. Use the value at arrayB[indexB] as her next index to hop back to arrayA.
  4. Stop when Gloria returns to her starting position.
  loop do
    indexB = arrayA[indexA] # Use Gloria's position in arrayA to find her next hop in arrayB
    max_value = arrayB[indexB] if arrayB[indexB] > max_value # Update max_value if necessary
    indexA = arrayB[indexB] # Update indexA to the value at arrayB[indexB]
    break if indexA == 0    # Stop when Gloria returns to her starting position
  end

This loop ensures Gloria hops correctly, updates her discoveries, and knows when her journey is complete.

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