Lookahead Autopilot for Canyon Gates

Medium · Software Engineering Fundamentals · Data Scientist · Online Assessment

Problem Statement

Implement a deterministic per-tick flight controller and simulation harness for a circular thruster craft navigating unseen sequences of vertical barrier walls.

Deterministic Physics & Collision Model

GRAVITY = 0.6    LIFT = 4.5    MAX_FALL = -8.0    SPEED = 3.0
RADIUS  = 3.0    FLOOR = 0.0   ROOF     = 120.0
START   = Drone(0.0, 60.0, 0.0)

The craft is a disc of radius RADIUS = 3.0 starting at START. On each discrete tick, the controller outputs a boolean thrust:

  • If thrust is True, vertical velocity vy is assigned LIFT (4.5) directly rather than added to the prior velocity.
  • If thrust is False, gravity accelerates the craft downward with terminal clamp: vy = max(vy - GRAVITY, MAX_FALL).
  • Position updates simultaneously to x = x + SPEED and y = y + vy.

A flight crashes immediately after a step whenever:

  • Floor or ceiling contact: y - RADIUS <= FLOOR or y + RADIUS >= ROOF, or
  • Barrier collision: for any wall Wall(x0, x1, low, high) whose horizontal interval [x0, x1] has strictly positive overlap with (x - RADIUS, x + RADIUS) (meaning x0 < x + RADIUS and x1 > x - RADIUS), the disc extends outside the rectangular pass-through window (y - RADIUS < low or y + RADIUS > high).

Required Interface

Wall, Drone, START, step(drone, thrust), and crashed(drone, walls) are provided in starter.py. Complete the four components below:

@dataclass(frozen=True)
class Wall:
    x0: float
    x1: float
    low: float
    high: float


@dataclass(frozen=True)
class Drone:
    x: float
    y: float
    vy: float


class Autopilot:
    def decide(self, drone: Drone, walls: List[Wall]) -> bool: ...


def fly(autopilot: Autopilot, walls: List[Wall], start: Drone = START) -> Tuple[bool, int]: ...
def random_canyon(rng: random.Random, n_walls: int) -> List[Wall]: ...
def run_harness(n_canyons: int = 100, n_walls: int = 10, seed: int = 0) -> Tuple[int, int]: ...
  1. Autopilot.decide(drone, walls): Given the current drone state and walls sorted by x0 containing every wall not yet completely cleared (x1 > drone.x - RADIUS), return True to fire the thruster or False to coast. Your controller will be evaluated across unseen randomized wall layouts where consecutive openings can jump sharply between low and high altitudes.
  2. fly(autopilot, walls, start=START): Advance drone from start tick by tick using step() and crashed(), passing remaining walls (x1 > drone.x - RADIUS) into autopilot.decide(). Return (True, ticks) as soon as the disc completely clears the final wall (drone.x - RADIUS >= walls[-1].x1), or (False, ticks) on the tick a crash occurs (returning (False, 0) if start already crashes and (True, 0) if walls is empty).
  3. random_canyon(rng, n_walls): Using rng exclusively for randomness (so identical seeds yield identical courses), generate n_walls sorted walls that at least one thrust sequence can clear from START. Every wall has width x1 - x0 == 18.0, the first x0 lies in [60.0, 90.0], consecutive x0 positions differ by [60.0, 90.0], and every window [low, high] sits within [0.0, 120.0] with height high - low >= 26.0.
  4. run_harness(n_canyons=100, n_walls=10, seed=0): Instantiate random.Random(seed), generate n_canyons courses of n_walls walls via random_canyon, fly an Autopilot through each, and return (cleared_count, n_canyons).

Examples

Example 1

walls = [
    Wall(66.0, 84.0, 14.0, 44.0),
    Wall(132.0, 150.0, 78.0, 108.0),
    Wall(198.0, 216.0, 16.0, 46.0),
]
# fly(Autopilot(), walls) -> (True, 73)

Walk-through: Starting at Drone(0.0, 60.0, 0.0), the craft descends into the low first window [14.0, 44.0], starts firing inside that window to climb 64 vertical units into the high second window [78.0, 108.0], and skims the lower edge of the second window so gravity can pull it back down into [16.0, 46.0]. At 3.0 horizontal units per tick, x - 3.0 reaches 216.0 at x = 219.0, completing the run on tick 73.

Example 2

walls = [
    Wall(72.0, 90.0, 82.0, 110.0),
    Wall(150.0, 168.0, 18.0, 48.0),
]
# fly(Autopilot(), walls) -> (True, 57)
# Coasting every tick (always False) -> (False, 14)
# Firing every tick (always True)    -> (False, 13)

Walk-through: Clearing the second wall (x1 = 168.0) requires x - 3.0 >= 168.0, which occurs at x = 171.0 on tick 57. Never firing from y = 60.0 drops the disc into the floor (y - 3.0 <= 0.0) on tick 14, while firing on every tick drives the disc into the ceiling (y + 3.0 >= 120.0) on tick 13.

Constraints

  • Mean execution time of Autopilot.decide must remain well under 10 ms per tick.
  • Autopilot.decide must be completely deterministic.
  • Canyon courses obey x1 - x0 == 18.0, 60.0 <= walls[0].x0 <= 90.0, 60.0 <= walls[i].x0 - walls[i - 1].x0 <= 90.0, 0.0 <= low < high <= 120.0, and high - low >= 26.0.

Step-by-step walkthrough

  1. Understand the physics and deliverables

    Each tick, the drone moves right by SPEED = 3.0 while our controller makes a single binary choice: - Fire thruster (True): Vertical velocity vy is set to LIFT = 4.5 (not added!). - Coast (False): Gravity subtracts GRAVITY = 0.6 down to a terminal fall speed MAX_FALL = -8.0.

    Then y updates by y + vy and x updates by x + 3.0. Because the drone is a disc of RADIUS = 3.0, it crashes if: - it touches the floor or roof (y - 3.0 <= 0.0 or y + 3.0 >= 120.0), or - its horizontal span (x - 3.0, x + 3.0) overlaps a wall [x0, x1] while y - 3.0 < wall.low or y + 3.0 > wall.high.

    We need to deliver both the controller and its evaluation harness (matching starter.py): - Autopilot.decide(drone, walls) -> bool: deterministic per-tick controller, well under 10 ms per call. - fly(autopilot, walls, start) -> (cleared, ticks): simulates a flight until the disc clears the last wall (x - 3.0 >= walls[-1].x1) or crashes. - random_canyon(rng, n_walls) -> List[Wall]: generates n_walls random feasible walls (18 thick, x0 spaced 60..90 apart, openings >= 26 tall). - run_harness(n_canyons, n_walls, seed) -> (cleared, n_canyons): scores Autopilot across n_canyons unseen canyons.

  2. Why simple threshold rules crash

    A tempting first attempt is to aim at the vertical midpoint of the next wall opening: "fire the thruster whenever coasting one tick would drop y below (wall.low + wall.high) / 2."

    That fails for two physics reasons: 1. Upward overshoot: Firing at y = 95 sets vy = +4.5. Even if you coast immediately afterward, the upward arc keeps rising (+4.5, +3.9, +3.3, +2.7, +2.1, +1.5, +0.9, +0.3 = +19.2 units total!) and slams the drone into the top of the opening. 2. Multi-wall transitions: In Example 1, Wall 2's opening is high (78..108 at x = 132..150) and Wall 3's opening is low (16..46 at x = 198..216). Only 48 horizontal units (16 ticks) separate the exit of Wall 2 from the front of Wall 3. If the drone exits Wall 2 high or still rising, gravity (0.6 acceleration per tick) cannot pull it down into 16..46 in time!

    Because the physics are deterministic and completely known, we do not need hand-tuned thresholds — we can simulate the consequences of both choices forward in time.

  3. Key idea: lookahead search with memoization

    Suppose we look H ticks ahead. At each tick there are 2 choices (coast or thrust), so naive branching explores 2^H sequences — for H = 70, 2^70 is roughly 10^21, which is impossible.

    However, notice that many different action sequences arrive at the exact same state: - At lookahead depth d, the drone's x coordinate is always drone.x + 3.0 * d, no matter which actions were taken! - Therefore, (d, round(y, 6), round(vy, 6)) completely determines the drone's future from depth d onward.

    If we already checked (d, y, vy) and proved that every continuation from it crashes before reaching H, we store that key in a dead set so we never explore it a second time. Two search-ordering choices keep the tree tiny: 1. Try coasting (False) before thrusting (True): If coasting has any surviving H-tick continuation, return False immediately without firing the thruster unnecessarily. 2. Stop as soon as one path reaches H: Most decisions only visit a few dozen states before finding a clean trajectory.

  4. Precompute the vertical corridor and reachability funnel

    Because xd = x + 3.0 * d is fixed for each depth d = 1..H, we do not need to loop over walls inside the recursive search. Before searching, _build_corridor computes the allowed vertical interval [wall_lo[d], wall_hi[d]] for each tick d once!

    We can also prune doomed branches early with a 3-line backward reachability funnel: - Since the drone can climb by at most max_climb = max(LIFT, drone.vy) (4.5 units) per tick, any state at tick d sitting lower than reach_lo[d + 1] - max_climb can never climb high enough to clear tick d + 1, even at full continuous thrust! - Since the drone can drop by at most -MAX_FALL (8.0 units) per tick, any state at tick d sitting higher than reach_hi[d + 1] + 8.0 can never drop fast enough to duck under tick d + 1!

     tick d=20      tick d=21      tick d=22      tick d=23 (Wall opening [82, 110])
                                                  wall_hi = 107.0 (= 110 - 3)
                    reach_hi=123   reach_hi=115   reach_hi=107.0
                                                     ^
                                                     |  (must stay inside [85, 107])
                                                     v
     reach_lo=71.5  reach_lo=76.0  reach_lo=80.5  wall_lo = 85.0  (= 82 + 3)
       (+4.5/tick ->  71.5 + 4.5 = 76.0 -> 80.5 -> 85.0)
    

    Finally, we run our check first with a tiny SAFETY_MARGIN = 0.05 so planned paths stay safely away from floating-point grazing (1e-15), and automatically fall back to margin = 0.0 if the only surviving path requires exact boundary clearance (y - 3.0 == wall.low).

    SAFETY_MARGIN = 0.05
    
    
    def _build_corridor(
        x: float,
        walls: List[Wall],
        ticks: int,
        margin: float,
        max_climb: float,
    ) -> Tuple[float, float, List[float], List[float], List[float], List[float]]:
        """Precompute per-tick collision bounds and backward-reachability bounds for d = 1..ticks."""
        # Floor and roof crash on `<=` and `>=`, so center y must stay strictly inside these limits.
        floor_limit = FLOOR + RADIUS + margin
        roof_limit = ROOF - RADIUS - margin
    
        # wall_lo[d], wall_hi[d]: inclusive [low + RADIUS, high - RADIUS] opening bounds at tick d
        wall_lo = [float("-inf")] * (ticks + 1)
        wall_hi = [float("inf")] * (ticks + 1)
    
        for d in range(1, ticks + 1):
            xd = x + SPEED * d
            for wall in walls:
                if wall.x0 >= xd + RADIUS:
                    break
                if wall.x1 > xd - RADIUS:
                    wall_lo[d] = max(wall_lo[d], wall.low + RADIUS + margin)
                    wall_hi[d] = min(wall_hi[d], wall.high - RADIUS - margin)
    
        # Backward reachability funnel: to survive all `ticks` steps, at step d the drone
        # cannot sit more than max_climb below reach_lo[d + 1] or -MAX_FALL above reach_hi[d + 1].
        reach_lo = [max(floor_limit, wall_lo[d]) for d in range(ticks + 1)]
        reach_hi = [min(roof_limit, wall_hi[d]) for d in range(ticks + 1)]
        for d in range(ticks - 1, 0, -1):
            reach_lo[d] = max(reach_lo[d], reach_lo[d + 1] - max_climb - 1e-9)
            reach_hi[d] = min(reach_hi[d], reach_hi[d + 1] - MAX_FALL + 1e-9)
    
        return floor_limit, roof_limit, wall_lo, wall_hi, reach_lo, reach_hi
    
  5. Code the autopilot search and doomed-state fallback

    Autopilot.decide has two clean phases: 1. Normal flight (_can_survive): For margin in (0.05, 0.0), test coast (False) first; if it can survive all horizon ticks, return False. Otherwise test thrust (True); if it can survive all horizon ticks, return True. 2. Doomed fallback (_max_ticks): If neither action survives the full horizon even with 0.0 margin (meaning a crash is unavoidable), compute the maximum number of ticks each choice survives using a memo dictionary memo[(d, rounded_y, rounded_vy)] and return thrust_ticks > coast_ticks.

    class Autopilot:
        """Depth-limited lookahead controller: coast when safe, thrust when needed."""
    
        def __init__(self, horizon: int = 70):
            self.horizon = horizon
    
        def decide(self, drone: Drone, walls: List[Wall]) -> bool:
            """Return True to fire the thruster on this tick, or False to coast."""
            max_climb = max(LIFT, drone.vy)
    
            # Phase 1: Try to survive the full horizon with SAFETY_MARGIN first, then 0.0 margin.
            for margin in (SAFETY_MARGIN, 0.0):
                corridor = _build_corridor(drone.x, walls, self.horizon, margin, max_climb)
                floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi = corridor
                # dead: set of (depth, rounded_y, rounded_vy) states proven unable to reach horizon
                dead: Set[Tuple[int, float, float]] = set()
    
                # Try coasting first: if coasting survives all `horizon` ticks, no thrust is needed.
                if self._can_survive(
                    0, drone.y, drone.vy, False,
                    floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
                ):
                    return False
                if self._can_survive(
                    0, drone.y, drone.vy, True,
                    floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
                ):
                    return True
    
            # Phase 2: Doomed state (no path clears the horizon even with 0.0 margin).
            # Pick whichever action keeps the drone airborne for strictly more ticks.
            memo: Dict[Tuple[int, float, float], int] = {}
            coast_ticks = self._max_ticks(
                0, drone.y, drone.vy, False, floor_lim, roof_lim, wall_lo, wall_hi, memo
            )
            thrust_ticks = self._max_ticks(
                0, drone.y, drone.vy, True, floor_lim, roof_lim, wall_lo, wall_hi, memo
            )
            return thrust_ticks > coast_ticks
    
  6. Choose the horizon length from canyon geometry

    How large must horizon be so the drone never traps itself inside one opening without seeing the next?

    Let us compute the worst-case horizontal distance from the drone's center x until its disc completely clears the second wall ahead:

    drone center x          Wall 1                  Wall 2
          O  <--- <= 90 ---> [x0 .. x1]              [x0 .. x1]
                             |<--18-->|              |<--18-->|
                             |<------ <= 90 -------->|
          |<---------------- <= 90 + 90 + 18 = 198 ---------->| (+ 3 radius = 201 units)
    
    • Wall 1's front face x0 is at most 90 units ahead.
    • Wall 2's front face x0 is at most another 90 units ahead (180 total).
    • Wall 2 is 18 units thick (x1 <= 198), and the drone's left edge x - 3 clears x1 3 units later (201 units total).
    • At SPEED = 3.0 units per tick, 201 / 3.0 = 67 ticks.

    Setting horizon = 70 guarantees the planner always sees all the way through the next two walls! Across 100 random 10-wall canyons (~25,600 decisions), horizon = 70 clears 100 / 100 canyons with a mean decision time under 0.1 ms and worst-case spikes around 3 ms — comfortably inside the 10 ms budget.

  7. Build the flight simulator and random canyon harness

    Now we assemble the testing harness: - fly(autopilot, walls, start) steps the drone tick by tick, advancing an index first_ahead past walls already cleared (wall.x1 <= drone.x - RADIUS) before calling autopilot.decide. - is_flyable(walls, start) runs the exact same _can_survive search with horizon = _ticks_to_clear(start.x, walls) spanning the entire canyon! - random_canyon(rng, n_walls) samples wall spacings in [60, 90] and opening heights in [26, 40] uniformly across [0, 120], redrawing the occasional physically impossible layout using is_flyable(walls) so run_harness measures controller skill rather than impossible maps.

    def _ticks_to_clear(x: float, walls: List[Wall]) -> int:
        """Count ticks until the drone's left edge (x - RADIUS) is at or past the last wall's x1."""
        ticks = 0
        while x + SPEED * ticks - RADIUS < walls[-1].x1:
            ticks += 1
        return ticks
    
    
    def fly(autopilot: Autopilot, walls: List[Wall], start: Drone = START) -> Tuple[bool, int]:
        """Fly one canyon tick by tick; return (cleared, ticks_flown)."""
        if crashed(start, walls):
            return False, 0
        if not walls:
            return True, 0
    
        drone = start
        ticks = 0
        first_ahead = 0
    
        while drone.x - RADIUS < walls[-1].x1:
            while walls[first_ahead].x1 <= drone.x - RADIUS:
                first_ahead += 1
            thrust = autopilot.decide(drone, walls[first_ahead:])
            drone = step(drone, thrust)
            ticks += 1
            if crashed(drone, walls):
                return False, ticks
    
        return True, ticks
    
  8. Trace the low-high-low example canyon

    Let us trace our Autopilot(horizon=70) on Example 1: - Wall(66.0, 84.0, low=14.0, high=44.0) (low) - Wall(132.0, 150.0, low=78.0, high=108.0) (high) - Wall(198.0, 216.0, low=16.0, high=46.0) (low)

    after tick    x       y     vy   what happens
    --------------------------------------------------------------------------------
        0        0.0    60.0    0.0  start in middle of canyon
       14       42.0     9.9   +4.5  single thrust arrests initial fall into Wall 1
       22       66.0    24.3   -0.3  coasts smoothly into Wall 1 (safe band [17.0, 41.0])
       27       81.0    21.6   +4.5  fires inside Wall 1 to start climbing toward Wall 2
       44      132.0    81.3   +4.5  enters Wall 2 just 0.3 above lower limit (81.0)!
       50      150.0    95.7   +0.9  coasts across Wall 2 so gravity can pull it down soon
       66      198.0    29.3   -8.0  drops 66.4 units in 16 ticks into Wall 3 ([19.0, 43.0])
       68      204.0    25.8   +4.5  arrests descent inside Wall 3
       73      219.0    39.3   +1.5  left edge x - 3 = 216.0 >= 216.0 -> CLEARED!
    

    Notice tick 44 and tick 50: because horizon = 70 already sees Wall 3 (16..46) before the drone even enters Wall 2 (78..108), the search deliberately skims the bottom of Wall 2 (y = 81.3) and coasts the entire way across so it starts dropping toward Wall 3 as early as physically possible!

  9. Complete solution

    from dataclasses import dataclass
    from typing import Dict, List, Set, Tuple
    import random
    
    # ---- The rules (known to the controller) ----
    
    GRAVITY = 0.6
    LIFT = 4.5
    MAX_FALL = -8.0
    SPEED = 3.0
    RADIUS = 3.0
    FLOOR = 0.0
    ROOF = 120.0
    
    
    @dataclass(frozen=True)
    class Wall:
        x0: float
        x1: float      # left and right faces
        low: float
        high: float    # vertical extent of the opening
    
    
    @dataclass(frozen=True)
    class Drone:
        x: float
        y: float
        vy: float
    
    
    START = Drone(0.0, 60.0, 0.0)
    
    
    def step(drone: Drone, thrust: bool) -> Drone:
        """Advance the drone by one tick."""
        if thrust:
            vy = LIFT
        else:
            vy = max(drone.vy - GRAVITY, MAX_FALL)
        return Drone(drone.x + SPEED, drone.y + vy, vy)
    
    
    def crashed(drone: Drone, walls: List[Wall]) -> bool:
        """True if the drone touches the floor or roof, or hits a wall outside its opening."""
        if drone.y - RADIUS <= FLOOR or drone.y + RADIUS >= ROOF:
            return True
        for wall in walls:
            if wall.x0 >= drone.x + RADIUS:
                break  # walls are sorted by x0: this one and all later ones are still ahead
            if wall.x1 > drone.x - RADIUS:  # the disc's x-range overlaps this wall
                if drone.y - RADIUS < wall.low or drone.y + RADIUS > wall.high:
                    return True
        return False
    
    
    # ---- Precomputed corridor and memoized lookahead search ----
    
    # Prefer paths with 0.05 clearance from walls/floor/roof so floating-point rounding
    # never turns a planned pass into a graze; fall back to 0.0 when exact contact is required.
    SAFETY_MARGIN = 0.05
    
    
    def _build_corridor(
        x: float,
        walls: List[Wall],
        ticks: int,
        margin: float,
        max_climb: float,
    ) -> Tuple[float, float, List[float], List[float], List[float], List[float]]:
        """Precompute per-tick collision bounds and backward-reachability bounds for d = 1..ticks.
    
        Because x advances by SPEED every tick regardless of actions, the exact x-position
        at depth d is x + SPEED * d. Precomputing wall_lo[d] and wall_hi[d] turns each
        collision check inside the search into O(1) float comparisons.
        """
        # Floor and roof crash on `<=` and `>=`, so center y must stay strictly inside these limits.
        floor_limit = FLOOR + RADIUS + margin
        roof_limit = ROOF - RADIUS - margin
    
        # wall_lo[d], wall_hi[d]: inclusive [low + RADIUS, high - RADIUS] opening bounds at tick d
        wall_lo = [float("-inf")] * (ticks + 1)
        wall_hi = [float("inf")] * (ticks + 1)
    
        for d in range(1, ticks + 1):
            xd = x + SPEED * d
            for wall in walls:
                if wall.x0 >= xd + RADIUS:
                    break
                if wall.x1 > xd - RADIUS:
                    wall_lo[d] = max(wall_lo[d], wall.low + RADIUS + margin)
                    wall_hi[d] = min(wall_hi[d], wall.high - RADIUS - margin)
    
        # Backward reachability funnel: to survive all `ticks` steps, at step d the drone
        # cannot sit more than max_climb below reach_lo[d + 1] or -MAX_FALL above reach_hi[d + 1].
        reach_lo = [max(floor_limit, wall_lo[d]) for d in range(ticks + 1)]
        reach_hi = [min(roof_limit, wall_hi[d]) for d in range(ticks + 1)]
        for d in range(ticks - 1, 0, -1):
            reach_lo[d] = max(reach_lo[d], reach_lo[d + 1] - max_climb - 1e-9)
            reach_hi[d] = min(reach_hi[d], reach_hi[d + 1] - MAX_FALL + 1e-9)
    
        return floor_limit, roof_limit, wall_lo, wall_hi, reach_lo, reach_hi
    
    
    class Autopilot:
        """Depth-limited lookahead controller: coast when safe, thrust when needed.
    
        horizon = 70 ticks (210 horizontal units) spans past the far face of the next
        two walls in the worst case: 90 + 90 + 18 + 3 = 201 units = 67 ticks.
        """
    
        def __init__(self, horizon: int = 70):
            self.horizon = horizon
    
        def decide(self, drone: Drone, walls: List[Wall]) -> bool:
            """Return True to fire the thruster on this tick, or False to coast."""
            max_climb = max(LIFT, drone.vy)
    
            # Phase 1: Try to survive the full horizon with SAFETY_MARGIN first, then 0.0 margin.
            for margin in (SAFETY_MARGIN, 0.0):
                corridor = _build_corridor(drone.x, walls, self.horizon, margin, max_climb)
                floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi = corridor
                # dead: set of (depth, rounded_y, rounded_vy) states proven unable to reach horizon
                dead: Set[Tuple[int, float, float]] = set()
    
                # Try coasting first: if coasting survives all `horizon` ticks, no thrust is needed.
                if self._can_survive(
                    0, drone.y, drone.vy, False,
                    floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
                ):
                    return False
                if self._can_survive(
                    0, drone.y, drone.vy, True,
                    floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
                ):
                    return True
    
            # Phase 2: Doomed state (no path clears the horizon even with 0.0 margin).
            # Pick whichever action keeps the drone airborne for strictly more ticks.
            # memo: maps (depth, rounded_y, rounded_vy) -> max remaining ticks survived
            memo: Dict[Tuple[int, float, float], int] = {}
            coast_ticks = self._max_ticks(
                0, drone.y, drone.vy, False, floor_lim, roof_lim, wall_lo, wall_hi, memo
            )
            thrust_ticks = self._max_ticks(
                0, drone.y, drone.vy, True, floor_lim, roof_lim, wall_lo, wall_hi, memo
            )
            return thrust_ticks > coast_ticks
    
        def _can_survive(
            self,
            d: int,
            y: float,
            vy: float,
            thrust: bool,
            floor_lim: float,
            roof_lim: float,
            wall_lo: List[float],
            wall_hi: List[float],
            reach_lo: List[float],
            reach_hi: List[float],
            dead: Set[Tuple[int, float, float]],
        ) -> bool:
            """Return True if taking `thrust` at depth d has a continuation surviving to horizon."""
            next_vy = LIFT if thrust else max(vy - GRAVITY, MAX_FALL)
            next_y = y + next_vy
    
            # Immediate crash check (strict on floor/roof, inclusive on wall openings) + funnel prune.
            if next_y <= floor_lim or next_y >= roof_lim:
                return False
            if next_y < wall_lo[d + 1] or next_y > wall_hi[d + 1]:
                return False
            if next_y < reach_lo[d + 1] or next_y > reach_hi[d + 1]:
                return False
            if d + 1 == self.horizon:
                return True
    
            key = (d + 1, round(next_y, 6), round(next_vy, 6))
            if key in dead:
                return False
    
            # Explore coast before thrust so we stop immediately on the calmest surviving trajectory.
            if self._can_survive(
                d + 1, next_y, next_vy, False,
                floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
            ):
                return True
            if self._can_survive(
                d + 1, next_y, next_vy, True,
                floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
            ):
                return True
    
            dead.add(key)
            return False
    
        def _max_ticks(
            self,
            d: int,
            y: float,
            vy: float,
            thrust: bool,
            floor_lim: float,
            roof_lim: float,
            wall_lo: List[float],
            wall_hi: List[float],
            memo: Dict[Tuple[int, float, float], int],
        ) -> int:
            """Return max ticks survived (out of horizon - d) when starting with `thrust` at depth d."""
            next_vy = LIFT if thrust else max(vy - GRAVITY, MAX_FALL)
            next_y = y + next_vy
    
            if next_y <= floor_lim or next_y >= roof_lim:
                return 0
            if next_y < wall_lo[d + 1] or next_y > wall_hi[d + 1]:
                return 0
            if d + 1 == self.horizon:
                return 1
    
            key = (d + 1, round(next_y, 6), round(next_vy, 6))
            if key not in memo:
                remaining = self.horizon - (d + 1)
                best = self._max_ticks(
                    d + 1, next_y, next_vy, False, floor_lim, roof_lim, wall_lo, wall_hi, memo
                )
                if best < remaining:
                    thrust_best = self._max_ticks(
                        d + 1, next_y, next_vy, True, floor_lim, roof_lim, wall_lo, wall_hi, memo
                    )
                    if thrust_best > best:
                        best = thrust_best
                memo[key] = best
    
            return 1 + memo[key]
    
    
    # ---- Flight simulator and random canyon harness ----
    
    def _ticks_to_clear(x: float, walls: List[Wall]) -> int:
        """Count ticks until the drone's left edge (x - RADIUS) is at or past the last wall's x1."""
        ticks = 0
        while x + SPEED * ticks - RADIUS < walls[-1].x1:
            ticks += 1
        return ticks
    
    
    def fly(autopilot: Autopilot, walls: List[Wall], start: Drone = START) -> Tuple[bool, int]:
        """Fly one canyon tick by tick; return (cleared, ticks_flown)."""
        if crashed(start, walls):
            return False, 0
        if not walls:
            return True, 0
    
        drone = start
        ticks = 0
        # first_ahead: index of the leftmost wall the drone has not completely cleared yet
        first_ahead = 0
    
        while drone.x - RADIUS < walls[-1].x1:
            while walls[first_ahead].x1 <= drone.x - RADIUS:
                first_ahead += 1
            thrust = autopilot.decide(drone, walls[first_ahead:])
            drone = step(drone, thrust)
            ticks += 1
            if crashed(drone, walls):
                return False, ticks
    
        return True, ticks
    
    
    def is_flyable(walls: List[Wall], start: Drone = START) -> bool:
        """Return True if some thrust sequence clears all walls with SAFETY_MARGIN clearance."""
        if crashed(start, walls):
            return False
        if not walls:
            return True
        ticks = _ticks_to_clear(start.x, walls)
        if ticks == 0:
            return True
    
        pilot = Autopilot(horizon=ticks)
        max_climb = max(LIFT, start.vy)
        corridor = _build_corridor(start.x, walls, ticks, SAFETY_MARGIN, max_climb)
        floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi = corridor
        dead: Set[Tuple[int, float, float]] = set()
    
        if pilot._can_survive(
            0, start.y, start.vy, False,
            floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
        ):
            return True
        return pilot._can_survive(
            0, start.y, start.vy, True,
            floor_lim, roof_lim, wall_lo, wall_hi, reach_lo, reach_hi, dead,
        )
    
    
    def random_canyon(rng: random.Random, n_walls: int) -> List[Wall]:
        """Generate n_walls random walls (18 thick, 60-90 apart, openings >= 26) that are flyable."""
        while True:
            walls: List[Wall] = []
            x0 = rng.uniform(60.0, 90.0)
            for _ in range(n_walls):
                opening_height = rng.uniform(26.0, 40.0)
                low = rng.uniform(FLOOR, ROOF - opening_height)
                walls.append(Wall(x0, x0 + 18.0, low, low + opening_height))
                x0 += rng.uniform(60.0, 90.0)
            # Reject impossible random draws so the harness measures the controller, not luck.
            if is_flyable(walls):
                return walls
    
    
    def run_harness(n_canyons: int = 100, n_walls: int = 10, seed: int = 0) -> Tuple[int, int]:
        """Fly a fresh Autopilot through n_canyons random canyons; return (cleared, n_canyons)."""
        rng = random.Random(seed)
        cleared = 0
        for _ in range(n_canyons):
            walls = random_canyon(rng, n_walls)
            ok, _ = fly(Autopilot(), walls)
            if ok:
                cleared += 1
        return cleared, n_canyons
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of steering a heavy boat with momentum through a narrow sequence of canal gates: you cannot teleport vertically, and firing your thruster gives an immediate upward kick (vy = +4.5) whose coasting arc keeps rising for 7 more ticks before gravity (0.6 per tick) even turns the drone back downward. Instead of guessing a rule of thumb like "fire below the middle of the next gate," we take advantage of the fact that the physics are 100% known and deterministic: before picking an action, we mentally fast-forward both choices (coast and thrust) across a lookahead horizon (a fixed window of future ticks simulated ahead of the current moment) that spans the next two walls.

Naive approaches fail in two opposite ways. A simple height threshold ("thrust if y is below the next opening's center") ignores momentum and future walls: it fires near the center of an opening and arcs straight into the ceiling, or exits a high opening still rising and misses a low opening right behind it. Conversely, brute-forcing every possible 70-tick sequence of coasts and thrusts explores 2^70 (~10^21) branches and times out immediately.

We make the search fast with memoization (caching states we have already evaluated so we never solve the same subproblem twice) and a reachability funnel (tightening each tick's allowed height range backwards using the drone's maximum climb rate +4.5 and terminal velocity, its capped fastest fall speed -8.0). Walk through a tiny 3-tick slice as the drone (RADIUS = 3.0) at x = 66, y = 80.0, vy = 2.1 approaches Example 2's Wall(72, 90, low=82, high=110) (where center y must lie in [85.0, 107.0] once x reaches 70..92):

  1. Precompute corridor: At d = 1 (x = 69.0), the disc [66, 72] only touches x0 = 72 at a point, so no wall applies yet; at d = 2 (x = 72.0), the disc [69, 75] overlaps the wall, requiring y in [85.0, 107.0]. Propagating backwards by max climb +4.5 tells d = 1 that y must already be at least 85.0 - 4.5 = 80.5.
  2. Test coast first: Coasting at d = 1 sets vy = 1.5, moving y to 81.5 (>= 80.5). Coasting again at d = 2 sets vy = 0.9, moving y to 82.4 < 85.0 (crash!), so the search tries thrust at d = 2: vy = 4.5, moving y to 86.0, safely inside [85.0, 107.0]!
  3. Commit one tick (receding-horizon control): Because coasting at d = 1 has a full 70-tick safe continuation, decide immediately returns False (coast) without even testing thrust at the root, and re-plans fresh from the new state on the next tick.

Complexity

  • Time per decision: O(H * W + S). Building the corridor scans H = 70 future ticks and checks only the first W walls near the drone (stopping as soon as wall.x0 >= xd + RADIUS). The search then visits S distinct (depth, rounded_y, rounded_vy) states, doing O(1) corridor bounds checks and at most two recursive calls per state because every dead state is recorded in dead (or memo when doomed). From START, vy takes at most 36 distinct values (4.5, 3.9, ..., -7.5 and 0.0, -0.6, ..., -8.0), and the backward funnel prunes unreachable heights immediately, so S typically stays under a few hundred states (~0.1 ms per call in Python).
  • Space: O(H + S). _build_corridor allocates four length-(H + 1) lists, recursion goes at most H frames deep, and dead / memo stores at most S tuples for the current call before being discarded.

Edge cases

  • Zero-clearance wall passes (y - RADIUS == wall.low or y + RADIUS == wall.high): decide tries SAFETY_MARGIN = 0.05 first so normal trajectories avoid floating-point boundary grazing, and falls back to margin = 0.0 whenever an exact boundary pass is the only way through.
  • Strict floor/roof vs. inclusive wall openings: Touching the floor (y - 3.0 <= 0.0) or roof (y + 3.0 >= 120.0) is a crash, whereas y - 3.0 == wall.low inside a wall opening is safe; _can_survive and _max_ticks mirror those exact <=/>= vs. </> comparisons.
  • Touching a wall face at a single point (x + RADIUS == x0 or x - RADIUS == x1): Positive horizontal overlap requires x + RADIUS > x0 and x - RADIUS < x1, matching crashed() on both entry and exit.
  • Unavoidable crashes (doomed states): When neither action can survive 70 ticks even with margin = 0.0, Phase 2 (_max_ticks) returns whichever action delays the crash longest, breaking ties in favor of coasting (False).
  • Empty wall list or already-crashed start: fly returns (False, 0) if start is already crashed and (True, 0) if walls is empty; Autopilot.decide with walls = [] safely avoids the floor and roof forever.

Common mistakes

  • Adding thrust (vy += LIFT) instead of setting vy = LIFT: Firing the thruster resets vertical velocity to +4.5 regardless of whether the drone was falling at -8.0 or already rising at +3.9.
  • Choosing a horizon shorter than two walls: With H = 25, the drone sails through the top of a high opening without seeing a low opening right behind it and cannot drop fast enough once Wall 2 enters view.
  • Omitting depth from the memoization key: The state (y = 50.0, vy = 0.0) at depth = 5 (x = x0 + 15) faces completely different walls than (y = 50.0, vy = 0.0) at depth = 20 (x = x0 + 60), so depth must be part of the key.
  • Hard-coding a safety margin without a zero-margin fallback: Adding 0.05 unconditionally rejects legal boundary-skimming paths when a tight entry leaves zero spare clearance.
  • Using a wall-clock timeout inside decide: Stopping a search after 8 ms of CPU clock time makes decisions depend on machine load, violating the determinism requirement; if you cap work, cap the number of visited states instead.

Alternative approaches

  • Whole-canyon offline plan: Because walls contains all remaining walls, running _can_survive once with horizon = _ticks_to_clear(...) produces a complete thrust schedule from start to finish in milliseconds, turning every subsequent decide call into an O(1) list lookup.
  • Breadth-first reachable sets: Maintain the set of reachable (round(y, 6), round(vy, 6)) pairs tick by tick from d = 0 to H. It avoids recursion altogether, though it expands every reachable state at every tick instead of exiting early on the first calm trajectory.
  • Backward dynamic programming: Sweep backwards from d = H down to 0 over the discretized (y, vy) grid, marking a state viable if at least one action lands in a viable state at d + 1.

Follow-up questions

  • How would you modify your planner if firing the thruster produced slightly noisy upward velocity on each tick? Because noisy thrust sets vy = LIFT + epsilon, any single thrust introduces velocity uncertainty that accumulates into height drift until the next thrust resets vy. For bounded noise epsilon in [-delta, +delta], propagate an interval [y_min, y_max] forward in the search (requiring the entire interval to stay inside [wall_lo, wall_hi]), and re-plan from the true measured drone state on every tick (receding-horizon control, executing only the first step of a plan and re-computing from fresh state observations at each tick). For unbounded Gaussian noise, evaluate a fixed set of deterministically seeded noise rollouts per action and pick the action with the highest survival probability and largest wall clearance.
  • Suppose each tick must return in under 1 millisecond; how would you balance lookahead depth against state discretization? Keep horizon = 70 first — dropping horizon to 30 causes crashes on steep high-to-low wall pairs — and cut constant factors before sacrificing lookahead depth. First, cache the surviving 70-tick action sequence from the previous tick: on the next tick, verify in O(1) whether extending that cached trajectory by 1 more tick still survives, avoiding 95%+ of full searches! Second, if a fresh search is needed, discretize y to 0.5-unit bins (with a matching 0.25 safety margin) and enforce a deterministic node-visit budget (say 1,500 states) so worst-case latency never exceeds 1 ms.
  • How could you synthesize adversarial yet solvable gate layouts to stress-test the controller? Use rejection sampling (generating candidates and keeping only those that pass a validity oracle) paired with local search around is_flyable: fix wall spacing near the minimum (60 units) and opening height near the minimum (26 units), then alternate extreme high and low openings and use binary search on each vertical jump until shifting an opening 1 unit further makes is_flyable return False. You can rank candidate canyons by bottleneck width — the minimum number of survivable (y, vy) states inside any wall — to surface razor-thin passages that expose off-by-one or horizon bugs.
  • Is it practical to replace online tree search with a precomputed lookup table, and what inputs would that table require? For a single known canyon, yes: a backward sweep over (tick, y_bin, vy_bin) (~300 ticks * 1,140 heights * 36 velocities ≈ 12.3M booleans, or ~1.5 MB bit-packed) gives an exact O(1) lookup policy, but it depends on the exact wall coordinates and cannot generalize to unseen canyons. An offline table for unseen canyons would have to key on relative features — (y, vy, dx_1, low_1, high_1, dx_2, low_2, high_2) (8 continuous dimensions) — which suffers from the curse of dimensionality as a dense table, so in practice you would either coarsen those features heavily or distill the online search planner into a small neural network via imitation learning.

Follow-up questions

Similar questions

More Aqr interview questions

All 3 Aqr questions →