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
thrustisTrue, vertical velocityvyis assignedLIFT(4.5) directly rather than added to the prior velocity. - If
thrustisFalse, gravity accelerates the craft downward with terminal clamp:vy = max(vy - GRAVITY, MAX_FALL). - Position updates simultaneously to
x = x + SPEEDandy = y + vy.
A flight crashes immediately after a step whenever:
- Floor or ceiling contact:
y - RADIUS <= FLOORory + 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)(meaningx0 < x + RADIUSandx1 > x - RADIUS), the disc extends outside the rectangular pass-through window (y - RADIUS < lowory + 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]: ...
Autopilot.decide(drone, walls): Given the currentdronestate andwallssorted byx0containing every wall not yet completely cleared (x1 > drone.x - RADIUS), returnTrueto fire the thruster orFalseto coast. Your controller will be evaluated across unseen randomized wall layouts where consecutive openings can jump sharply between low and high altitudes.fly(autopilot, walls, start=START): Advancedronefromstarttick by tick usingstep()andcrashed(), passing remaining walls (x1 > drone.x - RADIUS) intoautopilot.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)ifstartalready crashes and(True, 0)ifwallsis empty).random_canyon(rng, n_walls): Usingrngexclusively for randomness (so identical seeds yield identical courses), generaten_wallssorted walls that at least one thrust sequence can clear fromSTART. Every wall has widthx1 - x0 == 18.0, the firstx0lies in[60.0, 90.0], consecutivex0positions differ by[60.0, 90.0], and every window[low, high]sits within[0.0, 120.0]with heighthigh - low >= 26.0.run_harness(n_canyons=100, n_walls=10, seed=0): Instantiaterandom.Random(seed), generaten_canyonscourses ofn_wallswalls viarandom_canyon, fly anAutopilotthrough 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.decidemust remain well under10 msper tick. Autopilot.decidemust 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, andhigh - low >= 26.0.
Step-by-step walkthrough
Understand the physics and deliverables
Each tick, the drone moves right by
SPEED = 3.0while our controller makes a single binary choice: - Fire thruster (True): Vertical velocityvyis set toLIFT = 4.5(not added!). - Coast (False): Gravity subtractsGRAVITY = 0.6down to a terminal fall speedMAX_FALL = -8.0.Then
yupdates byy + vyandxupdates byx + 3.0. Because the drone is a disc ofRADIUS = 3.0, it crashes if: - it touches the floor or roof (y - 3.0 <= 0.0ory + 3.0 >= 120.0), or - its horizontal span(x - 3.0, x + 3.0)overlaps a wall[x0, x1]whiley - 3.0 < wall.lowory + 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 under10 msper 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]: generatesn_wallsrandom feasible walls (18thick,x0spaced60..90apart, openings>= 26tall). -run_harness(n_canyons, n_walls, seed) -> (cleared, n_canyons): scoresAutopilotacrossn_canyonsunseen canyons.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
ybelow(wall.low + wall.high) / 2."That fails for two physics reasons: 1. Upward overshoot: Firing at
y = 95setsvy = +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.2units 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..108atx = 132..150) and Wall 3's opening is low (16..46atx = 198..216). Only48horizontal units (16ticks) separate the exit of Wall 2 from the front of Wall 3. If the drone exits Wall 2 high or still rising, gravity (0.6acceleration per tick) cannot pull it down into16..46in 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.
Key idea: lookahead search with memoization
Suppose we look
Hticks ahead. At each tick there are2choices (coastorthrust), so naive branching explores2^Hsequences — forH = 70,2^70is roughly10^21, which is impossible.However, notice that many different action sequences arrive at the exact same state: - At lookahead depth
d, the drone'sxcoordinate is alwaysdrone.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 depthdonward.If we already checked
(d, y, vy)and proved that every continuation from it crashes before reachingH, we store that key in adeadset 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 survivingH-tick continuation, returnFalseimmediately without firing the thruster unnecessarily. 2. Stop as soon as one path reachesH: Most decisions only visit a few dozen states before finding a clean trajectory.Precompute the vertical corridor and reachability funnel
Because
xd = x + 3.0 * dis fixed for each depthd = 1..H, we do not need to loop overwallsinside the recursive search. Before searching,_build_corridorcomputes the allowed vertical interval[wall_lo[d], wall_hi[d]]for each tickdonce!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.5units) per tick, any state at tickdsitting lower thanreach_lo[d + 1] - max_climbcan never climb high enough to clear tickd + 1, even at full continuous thrust! - Since the drone can drop by at most-MAX_FALL(8.0units) per tick, any state at tickdsitting higher thanreach_hi[d + 1] + 8.0can never drop fast enough to duck under tickd + 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.05so planned paths stay safely away from floating-point grazing (1e-15), and automatically fall back tomargin = 0.0if 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_hiCode the autopilot search and doomed-state fallback
Autopilot.decidehas two clean phases: 1. Normal flight (_can_survive): Formarginin(0.05, 0.0), testcoast(False) first; if it can survive allhorizonticks, returnFalse. Otherwise testthrust(True); if it can survive allhorizonticks, returnTrue. 2. Doomed fallback (_max_ticks): If neither action survives the full horizon even with0.0margin (meaning a crash is unavoidable), compute the maximum number of ticks each choice survives using a memo dictionarymemo[(d, rounded_y, rounded_vy)]and returnthrust_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_ticksChoose the horizon length from canyon geometry
How large must
horizonbe 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
xuntil 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
x0is at most90units ahead. - Wall 2's front face
x0is at most another90units ahead (180total). - Wall 2 is
18units thick (x1 <= 198), and the drone's left edgex - 3clearsx13units later (201units total). - At
SPEED = 3.0units per tick,201 / 3.0 = 67ticks.
Setting
horizon = 70guarantees the planner always sees all the way through the next two walls! Across 100 random 10-wall canyons (~25,600 decisions),horizon = 70clears100 / 100canyons with a mean decision time under0.1 msand worst-case spikes around3 ms— comfortably inside the10 msbudget.- Wall 1's front face
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 indexfirst_aheadpast walls already cleared (wall.x1 <= drone.x - RADIUS) before callingautopilot.decide. -is_flyable(walls, start)runs the exact same_can_survivesearch withhorizon = _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 usingis_flyable(walls)sorun_harnessmeasures 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, ticksTrace 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
44and tick50: becausehorizon = 70already 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!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):
- Precompute corridor: At
d = 1(x = 69.0), the disc[66, 72]only touchesx0 = 72at a point, so no wall applies yet; atd = 2(x = 72.0), the disc[69, 75]overlaps the wall, requiringyin[85.0, 107.0]. Propagating backwards by max climb+4.5tellsd = 1thatymust already be at least85.0 - 4.5 = 80.5. - Test
coastfirst: Coasting atd = 1setsvy = 1.5, movingyto81.5(>= 80.5). Coasting again atd = 2setsvy = 0.9, movingyto82.4 < 85.0(crash!), so the search triesthrustatd = 2:vy = 4.5, movingyto86.0, safely inside[85.0, 107.0]! - Commit one tick (
receding-horizon control): Because coasting atd = 1has a full70-tick safe continuation,decideimmediately returnsFalse(coast) without even testingthrustat 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 scansH = 70future ticks and checks only the firstWwalls near the drone (stopping as soon aswall.x0 >= xd + RADIUS). The search then visitsSdistinct(depth, rounded_y, rounded_vy)states, doingO(1)corridor bounds checks and at most two recursive calls per state because every dead state is recorded indead(ormemowhen doomed). FromSTART,vytakes at most36distinct values (4.5, 3.9, ..., -7.5and0.0, -0.6, ..., -8.0), and the backward funnel prunes unreachable heights immediately, soStypically stays under a few hundred states (~0.1 msper call in Python). - Space:
O(H + S)._build_corridorallocates four length-(H + 1)lists, recursion goes at mostHframes deep, anddead/memostores at mostStuples for the current call before being discarded.
Edge cases
- Zero-clearance wall passes (
y - RADIUS == wall.lowory + RADIUS == wall.high):decidetriesSAFETY_MARGIN = 0.05first so normal trajectories avoid floating-point boundary grazing, and falls back tomargin = 0.0whenever 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, whereasy - 3.0 == wall.lowinside a wall opening is safe;_can_surviveand_max_ticksmirror those exact<=/>=vs.</>comparisons. - Touching a wall face at a single point (
x + RADIUS == x0orx - RADIUS == x1): Positive horizontal overlap requiresx + RADIUS > x0andx - RADIUS < x1, matchingcrashed()on both entry and exit. - Unavoidable crashes (doomed states): When neither action can survive
70ticks even withmargin = 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:
flyreturns(False, 0)ifstartis already crashed and(True, 0)ifwallsis empty;Autopilot.decidewithwalls = []safely avoids the floor and roof forever.
Common mistakes
- Adding thrust (
vy += LIFT) instead of settingvy = LIFT: Firing the thruster resets vertical velocity to+4.5regardless of whether the drone was falling at-8.0or 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
depthfrom the memoization key: The state(y = 50.0, vy = 0.0)atdepth = 5(x = x0 + 15) faces completely different walls than(y = 50.0, vy = 0.0)atdepth = 20(x = x0 + 60), sodepthmust be part of the key. - Hard-coding a safety margin without a zero-margin fallback: Adding
0.05unconditionally rejects legal boundary-skimming paths when a tight entry leaves zero spare clearance. - Using a wall-clock timeout inside
decide: Stopping a search after8 msof 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
wallscontains all remaining walls, running_can_surviveonce withhorizon = _ticks_to_clear(...)produces a complete thrust schedule from start to finish in milliseconds, turning every subsequentdecidecall into anO(1)list lookup. - Breadth-first reachable sets: Maintain the set of reachable
(round(y, 6), round(vy, 6))pairs tick by tick fromd = 0toH. 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 = Hdown to0over the discretized(y, vy)grid, marking a state viable if at least one action lands in a viable state atd + 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 resetsvy. For bounded noiseepsilonin[-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 measureddronestate 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 = 70first — droppinghorizonto30causes crashes on steep high-to-low wall pairs — and cut constant factors before sacrificing lookahead depth. First, cache the surviving70-tick action sequence from the previous tick: on the next tick, verify inO(1)whether extending that cached trajectory by1more tick still survives, avoiding95%+of full searches! Second, if a fresh search is needed, discretizeyto0.5-unit bins (with a matching0.25safety margin) and enforce a deterministic node-visit budget (say1,500states) so worst-case latency never exceeds1 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 (60units) and opening height near the minimum (26units), then alternate extreme high and low openings and use binary search on each vertical jump until shifting an opening1unit further makesis_flyablereturnFalse. 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.3Mbooleans, or~1.5 MBbit-packed) gives an exactO(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)(8continuous 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
- How would you modify your planner if firing the thruster produced slightly noisy upward velocity on each tick?
- Suppose each tick must return in under 1 millisecond; how would you balance lookahead depth against state discretization?
- How could you synthesize adversarial yet solvable gate layouts to stress-test the controller?
- Is it practical to replace online tree search with a precomputed lookup table, and what inputs would that table require?
Similar questions
- Side-Scrolling Bird Autopilot Across Variable Pipe Layouts
- Submarine Ballast Controller for Variable Reef Channels
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging