Hackbright Code Challenges

Monkey River Crossing: Solution

Monkey River Crossing: Solution

Problem

Monkey River Crossing

Whiteboard

Harder

Challenge

Medium

Concepts

Logic, Lists

Download

monkey-solution.zip


At any given point, the monkey has the same strategy: to jump to the earliest-time stone it can reach. If our monkey can jump up to three stones, and the next three stones are 2 am, 1am, and 4am, it should jump to the 1 am stone.

This strategy can be repeated until the monkey has reached the shore and then we just need to find the latest time we depended on to make the trip.

monkey.py
def earliest_arrival(jump_distance, stones):
    """Find the earliest time a monkey can jump across a river."""

    # START SOLUTION

    # Position of monkey (-1 = the start)
    pos = -1
    
    # The time of all stones landed on
    landings = []
    
    while pos + jump_distance < len(stones):

        # Where can we jump to
        possible_landings = stones[pos + 1:pos + jump_distance + 1]

        # Take the earliest-time stone and keep track of its time
        soonest_landing = min(possible_landings)
        landings.append(soonest_landing)
        
        # Get our new position
        # (since stones list is defined in the problem to be unique,
        # we can find index of new position by using `list.index` ---
        # if there were repeat times, we'd need to do this differently)
        pos = stones.index(soonest_landing) 
        
    # What was the latest time of a stone used?
    return max(landings)