Receding-Horizon Controller for a Sinking Drone
System DesignModel answerLast updated
Build a tick-by-tick autopilot that uses short deterministic lookahead to steer a sinking drone through a series of vertical gap obstacles.
Receding-Horizon Controller for a Sinking Drone
Background
You are building an autopilot for a small underwater drone in a side-scrolling obstacle course. The drone moves forward at a constant speed and continuously loses altitude due to buoyancy drift. Once per game tick your controller can fire a thruster, which instantly gives the drone a fixed upward kick; if the thruster is not fired the drone keeps sinking a little faster each tick. A series of wall pairs block the path — each pair has a narrow vertical gap the drone must pass through. Clipping any wall, the sea floor, or the water surface ends the run immediately.
Your task is to implement should_thrust, a function called once per tick that returns True to fire the thruster or False to let the drone drift.
Interface
from dataclasses import dataclass
@dataclass
class WallPair:
x_left: float # left edge of the wall pair
x_right: float # right edge of the wall pair
gap_lo: float # lower boundary of the safe gap (top of the bottom wall)
gap_hi: float # upper boundary of the safe gap (bottom of the top wall)
@dataclass
class DroneState:
x: float # horizontal position (drone center)
y: float # vertical position above the floor (drone center); increases upward
vy: float # current vertical velocity; positive means moving upward
walls: list # visible WallPairs, sorted by x_left
def should_thrust(state: DroneState) -> bool:
"""Called once per tick. Return True to fire the upward thruster."""
What is expected
Implement should_thrust so the drone clears a sequence of wall pairs on maps it has not been tuned to. The gap heights and positions vary between maps, so a solution hard-coded to one map's timing does not qualify.
Describe your overall approach, justify your choice of lookahead depth, explain how you handle the case where no action can save the drone, and analyse the time complexity of your solution.
Physics constants (assumed — confirm with your interviewer)
| Constant | Value | Meaning |
|---|---|---|
DRIFT | 1.0 | vy decreases by this each tick when not thrusting |
THRUST_VY | 3.0 | vy is set to this when thrusting |
SPEED | 1.0 | horizontal advance per tick (constant) |
DRONE_R | 0.5 | collision radius of the drone |
FLOOR | 0.0 | y-coordinate of the floor |
CEILING | 30.0 | y-coordinate of the water surface |
Clarifying questions to raise before coding
- Can the controller see all upcoming wall pairs or only the next one?
- Is there a per-tick compute budget the solution must respect?
- Should the function degrade gracefully on an already-unwinnable state, or can it assume the given state is always recoverable?
Hints
Hint 1
Because the physics are fully deterministic and the constants are known, you can simulate the future exactly — no probability or estimation needed. Think about what structure that gives you to exploit.
Hint 2
The key question is not just 'does this action survive the next tick?' but 'does this action leave me in a state where some sequence of future actions can still survive?' A short recursive search over the two choices per tick can answer that.
Hint 3
Prefer not thrusting when both options are safe — it conserves energy and avoids over-correction. Re-run the search from scratch every tick rather than committing to a plan; that way the controller adapts as walls come into view. Consider: how many ticks ahead do you need to look to react in time?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: receding-horizon feasibility search
Because the drone's physics are deterministic and all constants are known ahead of time, should_thrust can simulate the future exactly. On each tick, evaluate two candidate actions (thrust / don't thrust), and for each one ask: does there exist any sequence of future actions over the next H ticks that keeps the drone alive? If not thrusting has such a continuation, take it — it's the conservative choice and avoids over-correcting. Fall back to thrusting only when drifting would lead to certain doom within the horizon. Because this search runs from scratch every tick, the controller automatically adapts as walls scroll into view instead of committing to a stale plan.
This pattern is called a receding-horizon controller (or model-predictive control in control theory). The "model" here is the exact physics simulation.
Implementation
from dataclasses import dataclass
# Physics constants — confirm these with the interviewer
DRIFT = 1.0 # vy lost per tick without thrust
THRUST_VY = 3.0 # vy set to this when thrusting
SPEED = 1.0 # horizontal advance per tick
DRONE_R = 0.5 # collision radius
FLOOR = 0.0
CEILING = 30.0
@dataclass(frozen=True)
class WallPair:
x_left: float
x_right: float
gap_lo: float
gap_hi: float
@dataclass(frozen=True)
class DroneState:
x: float
y: float
vy: float
walls: tuple # frozen for hashing if memoisation is added later
def step(state: DroneState, thrust: bool) -> DroneState:
vy = THRUST_VY if thrust else state.vy - DRIFT
return DroneState(state.x + SPEED, state.y + vy, vy, state.walls)
def collides(state: DroneState) -> bool:
# Floor and ceiling check
if state.y - DRONE_R <= FLOOR or state.y + DRONE_R >= CEILING:
return True
# Wall overlap check
for wall in state.walls:
overlaps_x = wall.x_left <= state.x + DRONE_R and state.x - DRONE_R <= wall.x_right
if overlaps_x:
outside_gap = state.y - DRONE_R <= wall.gap_lo or state.y + DRONE_R >= wall.gap_hi
if outside_gap:
return True
return False
def has_safe_path(state: DroneState, depth: int) -> bool:
"""Return True if any action sequence of length `depth` keeps the drone alive."""
if depth == 0:
return True
for thrust in (False, True): # prefer not thrusting — try it first
nxt = step(state, thrust)
if not collides(nxt) and has_safe_path(nxt, depth - 1):
return True
return False
def should_thrust(state: DroneState, horizon: int = 14) -> bool:
# Try each action; take the first one that has a safe continuation
for thrust in (False, True):
nxt = step(state, thrust)
if not collides(nxt) and has_safe_path(nxt, horizon - 1):
return thrust
# No action survives the full horizon — at least avoid immediate collision
for thrust in (False, True):
if not collides(step(state, thrust)):
return thrust
return True # last resort
# --- Quick smoke test ---
if __name__ == "__main__":
walls = (
WallPair(10, 16, 6, 16),
WallPair(30, 36, 14, 24),
WallPair(50, 56, 4, 14),
WallPair(70, 76, 10, 20),
)
state = DroneState(0.0, 15.0, 0.0, walls)
for tick in range(120):
state = step(state, should_thrust(state))
if collides(state):
print(f"Collision at tick {tick}, y={state.y:.2f}")
break
else:
print(f"Cleared all walls. Final x={state.x:.1f}")
Running the smoke test prints Cleared all walls — the controller threads all four gaps without ever committing to a fixed plan.
Choosing the horizon
The horizon must be long enough that the next dangerous wall is fully inside the lookahead window while there is still time to change course. With SPEED = 1.0 and THRUST_VY = 3.0, the drone can climb roughly 3 units per tick but loses altitude without thrust, so reacting too late (horizon < ~8) leaves it unable to reach a high gap in time. A horizon of 14 comfortably covers the worst-case gap position given these physics; tuning it upward past ~20 adds compute with diminishing safety returns.
Handling unwinnable states
If both actions lead to doom within the horizon, the course itself may be physically unpassable — for example, a gap too narrow for the drone's radius, or a gap positioned so no thrust schedule can reach it given the current velocity. The controller degrades gracefully by falling back to surviving just the next tick. The right diagnosis is to audit whether the gap geometry, drift rate, and thrust strength are mutually compatible, not to assume the controller logic is wrong.
Complexity
has_safe_path explores a binary tree of depth horizon, so worst-case cost per tick is O(2^H). In practice calls short-circuit quickly — a safe path is usually found on the first branch tried. For large horizons, two optimisations are worth mentioning:
- Memoisation: round
(x, y, vy)to the nearest grid cell and cache results. Identical physical states reached by different action sequences only need to be evaluated once. - Greedy fallback: instead of exhaustive search, steer toward the vertical centre of the next visible gap. This is O(1) per tick but offers no formal survivability guarantee — it's a good trade-off once the horizon is long enough that compute cost matters more than the edge-case safety net.
Common mistakes
- Reacting one tick at a time: checking only whether the drone survives the next tick ignores that the drone may be drifting into a position it cannot escape before the wall arrives.
- Committing to a fixed plan: computing a plan at tick 0 and executing it blindly fails as soon as reality diverges even slightly from the simulation (floating-point drift, slightly different physics constants on different maps).
- Ignoring the collision radius: treating the drone as a point causes silent failures at gap edges, since the drone's body extends
DRONE_Rin every direction. - Tuning the horizon to one map: the horizon should be calibrated to the physics constants and worst-case gap spacing, not to the specific wall positions in one test map.