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?
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:
- Start at
arrayA[0](value2). - Hop to
arrayB[2](value3). - Hop to
arrayA[3](value1). - Hop to
arrayB[1](value0). - Return to
arrayA[0], completing her journey.
The highest value Gloria encounters in arrayB is 3.
Before Gloria sets out on her hopping adventure, we must initialize:
indexAto track her current position inarrayA.max_valueto store the highest value she encounters during the journey.
These variables are Gloria’s essential tools for navigating her journey and recording her discoveries.
To guide Gloria through her journey:
- Use the value at
arrayA[indexA]as an index to hop toarrayB. - Update
max_valueif Gloria finds a new highest value inarrayB. - Use the value at
arrayB[indexB]as her next index to hop back toarrayA. - Stop when Gloria returns to her starting position.
This loop ensures Gloria hops correctly, updates her discoveries, and knows when her journey is complete.
