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:

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.

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.

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

Step 3 - Everything Together

Here’s the complete method to guide Gloria on her quest. It combines initialization, the main loop, and the final return statement:

This method efficiently computes the highest value Gloria discovers during her hopping journey.

Lesson Summary

Congratulations! You’ve successfully guided Gloria through her adventure, helping her navigate between two arrays and track the maximum value encountered. By dividing the task into clear steps—initialization, a traversal loop, and the final return—you’ve strengthened your problem-solving and coding skills.

Keep practicing, and may Gloria’s adventures inspire your journey as a programmer! Happy coding!

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