Submarine Ballast Controller for Variable Reef Channels
Medium · Software Engineering Fundamentals · Data Scientist · Online Assessment
Problem Statement
Implement an automated vertical-control policy for an underwater vessel advancing through horizontal reef corridors. On each discrete clock tick, the vessel moves rightward at constant speed while negative buoyancy pulls it downward unless it vents ballast, which immediately resets its vertical velocity to a fixed upward speed. Vertical reef formations jut upward from the sea floor and hang downward from the ocean surface in aligned pairs, leaving a rectangular pass-through window between them. Touching the sea floor, the surface layer, or the solid body of any reef terminates the voyage.
Your function should_surface(state) is invoked once per tick and must return True to vent ballast or False to let the vessel drift downward:
from dataclasses import dataclass
from typing import List
SINK_RATE = 0.5 # vertical speed lost on each non-ballast tick
BALLAST_VY = 3.0 # upward vertical speed set when venting ballast
SPEED = 2.0 # rightward advance per tick
SUB_RADIUS = 1.5 # half-width and half-height of the vessel's square hitbox
FLOOR_Y = 1.0 # upper boundary of the lethal sea-floor layer
SURFACE_Y = 59.0 # lower boundary of the lethal surface layer
@dataclass
class Reef:
x_left: float # left x-boundary of the reef formation
x_right: float # right x-boundary of the reef formation
gap_bottom: float # upper edge of the lower reef
gap_top: float # lower edge of the upper reef
@dataclass
class SubState:
x: float # current horizontal center of the vessel
y: float # current vertical center (grows upward toward SURFACE_Y)
vy: float # current vertical velocity per tick
reefs: List[Reef] # currently visible reef formations, ordered by ascending x_left
def should_surface(state: SubState) -> bool:
"""Return True to vent ballast on this tick, or False to drift downward."""
Each tick updates the simulation in the following exact order:
- Velocity update: Returning
Truesetsvy = BALLAST_VY(3.0); returningFalsesetsvy = vy - SINK_RATE(vy - 0.5). - Position update:
ybecomesy + vy, andxbecomesx + SPEED(x + 2.0). - Collision test: Modeling the vessel as the axis-aligned square
[x - SUB_RADIUS, x + SUB_RADIUS] x [y - SUB_RADIUS, y + SUB_RADIUS](3.0 x 3.0), the run ends after the move if:y - SUB_RADIUS <= FLOOR_Y(contacts the sea floor, i.e.,y <= 2.5),y + SUB_RADIUS >= SURFACE_Y(contacts the surface layer, i.e.,y >= 57.5), or- for any reef overlapping
[x - SUB_RADIUS, x + SUB_RADIUS]horizontally (x + SUB_RADIUS >= reef.x_leftandx - SUB_RADIUS <= reef.x_right), the hitbox does not sit strictly inside the vertical window (y - SUB_RADIUS <= reef.gap_bottomory + SUB_RADIUS >= reef.gap_top).
All physics parameters are deterministic, identical across courses, and known up front; state.reefs contains the reefs within forward sensor range sorted by x_left. One controller must navigate unseen courses whose window depths, heights, and spacings shift arbitrarily. Even when no action sequence can avoid an eventual crash, should_surface must still return a bool and survive as many ticks as possible.
Examples
Example 1
Input:
state = SubState(
x=4.0,
y=18.0,
vy=-0.5,
reefs=[Reef(x_left=13.0, x_right=23.0, gap_bottom=27.5, gap_top=46.0)],
)
Output:
True
Explanation: Moving at SPEED = 2.0 with SUB_RADIUS = 1.5, the vessel's front edge (x + 1.5) reaches x_left = 13.0 on tick 4 (x = 12.0, spanning [10.5, 13.5]), where center y must exceed 27.5 + 1.5 = 29.0. Drifting downward on tick 1 drops to y = 17.0 (vy = -1.0); even venting ballast on ticks 2, 3, and 4 climbs only to 20.0 -> 23.0 -> 26.0 <= 29.0, colliding with the lower reef. Venting ballast immediately climbs 21.0 -> 24.0 -> 27.0 -> 30.0 > 29.0 and clears the window.
Example 2
Input:
state = SubState(
x=0.0,
y=34.0,
vy=0.0,
reefs=[Reef(x_left=18.0, x_right=26.0, gap_bottom=16.0, gap_top=38.0)],
)
Output:
False
Explanation: Drifting downward on tick 1 moves to (x = 2.0, y = 33.5, vy = -0.5) and preserves a completely safe multi-tick path through the upcoming safe center interval (17.5, 36.5) while keeping room to descend if a deep opening follows.
Example 3
Input:
Start at (x=0.0, y=30.0, vy=0.0) across the full channel:
reefs = [
Reef(x_left=24.0, x_right=32.0, gap_bottom=35.0, gap_top=54.0),
Reef(x_left=56.0, x_right=64.0, gap_bottom=5.0, gap_top=23.0),
Reef(x_left=88.0, x_right=96.0, gap_bottom=31.0, gap_top=50.0),
]
Output:
Survives all 50 ticks until the hitbox clears x_right = 96.0
Explanation: The vessel climbs into the shallow upper window (36.5, 52.5), begins sinking near the bottom of that window so downward speed builds across the 24.0-unit gap before x = 56.0, threads the deep window (6.5, 21.5), and vents ballast to climb into (32.5, 48.5).
Constraints
SINK_RATE = 0.5,BALLAST_VY = 3.0,SPEED = 2.0,SUB_RADIUS = 1.5,FLOOR_Y = 1.0,SURFACE_Y = 59.0.state.reefsis sorted in non-decreasing order ofx_left, withreef.x_left < reef.x_rightandFLOOR_Y < reef.gap_bottom < reef.gap_top < SURFACE_Y.- Boundary contact (
<=againstFLOOR_Yorgap_bottom,>=againstSURFACE_Yorgap_topduring horizontal overlap) is a crash. should_surfacemust always return abool(TrueorFalse), use only the Python standard library, and finish well within a few milliseconds per tick even on inescapable states.
Step-by-step walkthrough
Pin down the physics and collision rules
Before designing the search, write down the exact one-tick equations and boundary rules (matching
starter.py):- Vertical and horizontal motion: On each tick, venting ballast (
True) setsvy = BALLAST_VY = 3.0; drifting downward (False) subtractsSINK_RATE = 0.5fromvy. Next,y += vyandx += SPEED = 2.0. - Collision box: The vessel is a
3 x 3square (SUB_RADIUS = 1.5). The sea floor sits atFLOOR_Y = 1.0and the surface sits atSURFACE_Y = 59.0, so centerymust remain strictly inside(2.5, 57.5). Contacting any boundary ends the run: overlapping a reef horizontally (x + 1.5 >= reef.x_leftandx - 1.5 <= reef.x_right) crashes whenevery - 1.5 <= reef.gap_bottomory + 1.5 >= reef.gap_top. - Visibility & inescapable states:
should_surfaceinspectsstate.reefs(sorted byx_left) and must always return abool— delaying an unavoidable crash as long as possible rather than raising an error.
Notice a key asymmetry in the vessel's vertical dynamics:
1 blow then sink (dy): +3.0, +5.5, +7.5, +9.0, +10.0, +10.5, +10.5, +10.0, ..., 0.0 (13 ticks) sink from rest (dy): -0.5, -1.5, -3.0, -5.0, -7.5, -10.5, -14.0, -18.0, -22.5, -27.5Climbing starts immediately at full speed (
+3.0on the very first tick), whereas sinking from rest starts at-0.5and needs several consecutive ticks to build downward speed. That asymmetry guides our entire tie-breaking strategy.- Vertical and horizontal motion: On each tick, venting ballast (
Model one tick and reef collisions
Because all parameters are deterministic and known, our foundation is an exact single-tick vertical step (
tick) and hitbox collision check (hits_something).In
hits_something,reefsis sorted byx_left: as soon asreef.x_left > x + r, neither this reef nor any subsequent reef can overlap the hitbox, so webreakimmediately.from typing import Dict, List, Set, Tuple from dataclasses import dataclass SINK_RATE = 0.5 BALLAST_VY = 3.0 SPEED = 2.0 SUB_RADIUS = 1.5 FLOOR_Y = 1.0 SURFACE_Y = 59.0 @dataclass class Reef: x_left: float x_right: float gap_bottom: float gap_top: float @dataclass class SubState: x: float y: float vy: float reefs: List[Reef] def tick(y: float, vy: float, blow: bool) -> Tuple[float, float]: """Advance vertical state by one tick: update velocity first, then height.""" if blow: next_vy = BALLAST_VY else: next_vy = vy - SINK_RATE next_y = y + next_vy return next_y, next_vy def hits_something(x: float, y: float, reefs: List[Reef]) -> bool: """Return True if the sub's box at (x, y) touches the floor, surface, or a reef.""" r = SUB_RADIUS if y - r <= FLOOR_Y or y + r >= SURFACE_Y: return True for reef in reefs: if reef.x_left > x + r: break if reef.x_right >= x - r: if y - r <= reef.gap_bottom or y + r >= reef.gap_top: return True return FalseWhy reactive rules and 1-tick checks fail
Trace Example 1:
x = 4.0, y = 18.0, vy = -0.5facingReef(x_left=13.0, x_right=23.0, gap_bottom=27.5, gap_top=46.0). AtSPEED = 2.0, the vessel's hitbox (r = 1.5) reachesx_left = 13.0on tick4(x = 12.0, right edge13.5 >= 13.0), where centeryneedsy > 27.5 + 1.5 = 29.0:tick: 1 2 3 4 (overlaps reef at x = 12.0) blow, blow, blow, blow: 21.0, 24.0, 27.0, 30.0 -> 30.0 > 29.0 (SAFE!) sink, blow, blow, blow: 17.0, 20.0, 23.0, 26.0 -> 26.0 <= 29.0 (CRASH!)Drifting downward on tick
1(y = 17.0) hits nothing immediately, yet even venting ballast on all three remaining ticks can no longer reach29.0. Likewise, a reactive midpoint rule ("vent ballast wheneveryis below the next opening's midpoint") hovers high inside Example 3's first window (35..54) and cannot build downward speed fast enough to make the deep second window (5..23).Why unmemoized lookahead explodes near dead ends
To plan
HORIZON = 30ticks ahead, naive recursion tries(False, True)at every tick. In open water, the very first all-sink/occasional-blow path reaches30ticks immediately.Whenever a branch is unescapable, however — such as testing whether
sinkcan clear a steep reef25ticks ahead when it physically cannot — unmemoized recursion must exhaust every combination of sinks and blows before proving failure (2^25to2^30branches, stalling a single tick for hundreds of milliseconds). That slowdown strikes right near narrow gaps and walls.Key idea: memoize maximum ticks survived per state
Distinct sequences of ballast actions frequently converge on the exact same state: - Within one
should_surfacecall, horizontal positionxatticks_leftremaining ticks is alwaysstate.x + (HORIZON - ticks_left) * SPEED. - Consequently,(ticks_left, round(y, 6), round(vy, 6))completely identifies the subproblem.Count how many distinct states can appear across
30ticks: -ticks_left:1 .. 29(< 30values). -vyaftertticks: eithervy_0 - 0.5 * tor3.0 - 0.5 * k(kticks since the last blow), at mostt + 1 <= 31values. - Half-integerystrictly inside(2.5, 57.5): at most109heights (3.0, 3.5, ..., 57.0).That bounds the entire search graph by
30 * 31 * 109 ≈ 101,000states instead of2^30 ≈ 1.07 billionbranches. Caching integermax_ticks_survived(0 .. ticks_left) inmemoand breaking as soon asbest == ticks_leftachieves two goals at once: 1. On survivable states, the search stops on the first30-tick trajectory (~50recursive calls on average). 2. On doomed states, a single memoized pass computes the exact maximum survival ticks for both actions without repeating shorter-horizon searches.HORIZON = 30 # ticks of lookahead (60 horizontal units) def max_ticks_survived( x: float, y: float, vy: float, ticks_left: int, reefs: List[Reef], memo: Dict[Tuple[int, float, float], int], ) -> int: """Return the maximum number of ticks (out of `ticks_left`) survivable from (x, y, vy).""" if ticks_left == 0: return 0 key = (ticks_left, round(y, 6), round(vy, 6)) if key in memo: return memo[key] best = 0 for blow in (False, True): next_y, next_vy = tick(y, vy, blow) next_x = x + SPEED if hits_something(next_x, next_y, reefs): continue survived = 1 + max_ticks_survived( next_x, next_y, next_vy, ticks_left - 1, reefs, memo ) if survived > best: best = survived if best == ticks_left: break memo[key] = best return bestScore both choices: prefer sinking and re-plan every tick
On every call to
should_surface(state): 1. Evaluatesink(False) first: Whensink_ticks == HORIZON(as in Example 2 aty = 34.0, vy = 0.0), drifting downward preserves a safe30-tick future, so we immediately returnFalsewithout searchingblow. 2. Why default to sinking? Because climbing is instantaneous (+3.0) whereas sinking accelerates gradually (-0.5/tick), staying lower whenever safe preserves maximum downward agility for sudden deep reef openings. 3. Evaluateblow(True) sharingmemo: Bothscore_action(state, False, memo)andscore_action(state, True, memo)entermax_ticks_survivedatticks_left = HORIZON - 1(next_x = state.x + SPEED), so sharing onememodictionary is 100% valid. Returningblow_ticks > sink_tickspicks ballast whenever sinking fails (blow_ticks == HORIZON > sink_ticks) or when doomed and ballast survives strictly longer, and returnsFalseon ties (including0 == 0).Re-planning from scratch on every tick (receding-horizon control) lets newly visible reefs steer the vessel smoothly.
def score_action( state: SubState, blow: bool, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return ticks survived (out of HORIZON) if the sub chooses `blow` now and plays optimally.""" next_y, next_vy = tick(state.y, state.vy, blow) next_x = state.x + SPEED if hits_something(next_x, next_y, state.reefs): return 0 return 1 + max_ticks_survived( next_x, next_y, next_vy, HORIZON - 1, state.reefs, memo ) def should_surface(state: SubState) -> bool: """Called once per tick. Return True to blow ballast on this tick, or False to sink.""" memo: Dict[Tuple[int, float, float], int] = {} sink_ticks = score_action(state, False, memo) if sink_ticks == HORIZON: return False blow_ticks = score_action(state, True, memo) return blow_ticks > sink_ticksChoose the horizon and trace the hardest reef patterns
Climbing nearly the entire
55-unit water column at+3.0per tick takes~19ticks, and traversing a10..12-wide reef takes~7ticks, totaling~26ticks. ChoosingHORIZON = 30(60horizontal units) comfortably spans full-column climbs and steep dives in well under1.5 msper tick:- Example 3 transition — shallow upper window (
35..54atx = 24..32), then deep window (5..23atx = 56..64): Only24horizontal units (12ticks) separate the two formations, requiring a descent fromy > 36.5down toy < 21.5while leveling out beforegap_bottom = 5. WithHORIZON = 30, the planner sees Reef 2 before entering Reef 1, skims the lower edge of Reef 1 already sinking, and arrests its dive cleanly inside Reef 2. - Window barely taller than the vessel (
Reef(26, 30, gap_bottom=33, gap_top=38), height5for a3-tall hitbox fromy = 25.0, vy = 0.0): Across the3ticks overlapping[26, 30], centerymust stay strictly inside(34.5, 36.5)— leaving only35.0, 35.5, 36.0on the0.5grid! Venting inside the opening jumps+3.0, so the vessel must drift across the opening right along the flat crest of a ballast hop (+10.0, +10.5, +10.5->35.0, 35.5, 35.5). Shifting that window down by1unit (gap_bottom = 32) makes the course physically unsolvable from(y = 25.0, vy = 0.0), highlighting why test maps should always be checked with a reachability oracle first.
- Example 3 transition — shallow upper window (
Complete solution
from typing import Dict, List, Set, Tuple from dataclasses import dataclass # Physics, known in advance and the same on every map. SINK_RATE = 0.5 # vy drops by this much on a tick without ballast BALLAST_VY = 3.0 # blowing ballast sets vy to this value SPEED = 2.0 # x advances by this much every tick SUB_RADIUS = 1.5 # half-size of the sub's collision box FLOOR_Y = 1.0 # top of the sea-floor layer SURFACE_Y = 59.0 # bottom of the surface layer HORIZON = 30 # ticks of lookahead (60 horizontal units) @dataclass class Reef: x_left: float # left edge of the reef pair x_right: float # right edge of the reef pair gap_bottom: float # top of the lower reef gap_top: float # bottom of the upper reef @dataclass class SubState: x: float # sub's horizontal position (center) y: float # sub's height above the floor (center); y grows upward vy: float # vertical velocity this tick; positive means rising reefs: List[Reef] # reefs the controller can see, sorted by x_left def tick(y: float, vy: float, blow: bool) -> Tuple[float, float]: """Advance vertical state by one tick: update velocity first, then height.""" if blow: next_vy = BALLAST_VY else: next_vy = vy - SINK_RATE next_y = y + next_vy return next_y, next_vy def hits_something(x: float, y: float, reefs: List[Reef]) -> bool: """Return True if the sub's box at (x, y) touches the floor, surface, or a reef.""" r = SUB_RADIUS # Touching the floor layer (y - r <= FLOOR_Y) or surface layer (y + r >= SURFACE_Y) crashes. if y - r <= FLOOR_Y or y + r >= SURFACE_Y: return True for reef in reefs: # reefs is sorted by x_left: stop scanning once reefs lie strictly ahead of our box. if reef.x_left > x + r: break if reef.x_right >= x - r: # Horizontally overlapping: safe only when strictly inside (gap_bottom, gap_top). if y - r <= reef.gap_bottom or y + r >= reef.gap_top: return True return False def max_ticks_survived( x: float, y: float, vy: float, ticks_left: int, reefs: List[Reef], memo: Dict[Tuple[int, float, float], int], ) -> int: """Return the maximum number of ticks (out of `ticks_left`) survivable from (x, y, vy).""" if ticks_left == 0: return 0 # Within one should_surface call, x is uniquely fixed by `ticks_left` # (x = state.x + (HORIZON - ticks_left) * SPEED), so (ticks_left, y, vy) identifies the state. key = (ticks_left, round(y, 6), round(vy, 6)) if key in memo: return memo[key] best = 0 # Try sinking (False) before blowing ballast (True) to stop on the first calm safe path. for blow in (False, True): next_y, next_vy = tick(y, vy, blow) next_x = x + SPEED if hits_something(next_x, next_y, reefs): continue survived = 1 + max_ticks_survived( next_x, next_y, next_vy, ticks_left - 1, reefs, memo ) if survived > best: best = survived if best == ticks_left: # Early exit: already survived the entire remaining horizon! break memo[key] = best return best def score_action( state: SubState, blow: bool, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return ticks survived (out of HORIZON) if the sub chooses `blow` now and plays optimally.""" next_y, next_vy = tick(state.y, state.vy, blow) next_x = state.x + SPEED if hits_something(next_x, next_y, state.reefs): return 0 return 1 + max_ticks_survived( next_x, next_y, next_vy, HORIZON - 1, state.reefs, memo ) def should_surface(state: SubState) -> bool: """Called once per tick. Return True to blow ballast on this tick, or False to sink.""" # memo: maps (ticks_left, rounded_y, rounded_vy) -> max remaining ticks survived. # Shared safely between sink and blow because both start recursion at ticks_left = HORIZON - 1. memo: Dict[Tuple[int, float, float], int] = {} # Prefer sinking: rising is instant (+3.0), whereas sinking builds speed slowly (-0.5/tick), # so staying lower until ballast is needed preserves maneuverability for steep drops. sink_ticks = score_action(state, False, memo) if sink_ticks == HORIZON: return False blow_ticks = score_action(state, True, memo) # Returns True if blowing reaches HORIZON (since sink_ticks < HORIZON), or if doomed # and blowing delays the crash strictly longer; returns False on ties (including 0 == 0). return blow_ticks > sink_ticks✅ Submit now — all tests should pass.
Intuition & how it works
Imagine steering a small submersible through submerged stone arches: venting ballast gives an instant upward velocity (vy = +3.0), whereas downward drift builds gradually (-0.5 per tick). Because every equation of motion is deterministic and known, we never need a fragile rule like "vent ballast whenever below the middle of the next opening." Instead, on each tick, we simulate both choices (sink vs. blow) forward across a lookahead horizon (a fixed window of future ticks simulated ahead of the present state) and continue sinking unless sinking traps the vessel before the horizon ends.
Naive strategies fail in two opposite ways. Aiming at the vertical midpoint of the nearest reef opening ignores asymmetric vertical acceleration, leaving the vessel far too high after a shallow arch to dive into a deep arch right behind it. Conversely, exploring all 2^30 (~1.07 billion) action sequences over 30 ticks without caching stalls for hundreds of milliseconds whenever the search hits an unpassable branch.
We overcome both issues with memoization (caching the maximum survivable ticks for each (ticks_left, y, vy) tuple so equivalent states reached via different ballast histories are solved once) and receding-horizon control (executing only the current tick's decision and re-planning fresh on the next tick). Trace Example 1 from x = 4.0, y = 18.0, vy = -0.5 approaching Reef(x_left=13.0, x_right=23.0, gap_bottom=27.5, gap_top=46.0) (4 ticks away at x = 12.0, where the 3 x 3 axis-aligned bounding box, [x - 1.5, x + 1.5] x [y - 1.5, y + 1.5], needs center y > 29.0):
- Test
sink(False) first: Sinking on tick1moves to(x = 6.0, y = 17.0, vy = -1.0). Even if the vessel vents ballast on ticks2, 3, 4(+3.0each tick), center height reaches20.0 -> 23.0 -> 26.0 <= 29.0, hitting the lower reef on tick4(sink_ticks = 3 < 30). - Test
blow(True) next: Venting ballast on ticks1, 2, 3, 4climbs21.0 -> 24.0 -> 27.0 -> 30.0 > 29.0, entering the window cleanly and surviving all30ticks (blow_ticks = 30). - Commit and re-plan:
should_surfacereturnsTruenow and runs a fresh search from the updatedSubStateon the next tick.
Complexity
- Time per call:
O(S * P)in both normal and doomed states. HereSis the number of distinct(ticks_left, rounded_y, rounded_vy)states visited andPis the number of nearby reefs inspected byhits_somethingbefore breaking atreef.x_left > x + r. AcrossHORIZON = 30ticks,ticks_lefttakes< 30values,vytakes at most31values, and0.5-spaced heights inside(2.5, 57.5)take at most109values, boundingSby~101,000states (versus2^30 ≈ 1.07 billionraw sequences). Survivable calls exit on the first30-tick trajectory (~50states on average), and even inescapable states finish in a single shared-memo pass. - Space:
O(S + HORIZON).memoholds at mostSentries during oneshould_surfacecall, and recursion depth never exceedsHORIZON = 30; zero state persists across ticks.
Edge cases
- Open water (
reefs = []): OnlyFLOOR_Y = 1.0andSURFACE_Y = 59.0constrain vertical motion; the vessel drifts downward peacefully, vents ballast right abovey = 2.5, and repeats forever. - Immediate unavoidable collision (
sink_ticks == 0andblow_ticks == 0): Aty = 56.0, vy = 4.0, sinking moves to59.5and venting moves to59.0, both hittingSURFACE_Y = 59.0(y + 1.5 >= 59.0).blow_ticks > sink_ticks(0 > 0) cleanly returnsFalse. - Doomed several ticks ahead: When an unpassable reef lies within the horizon,
blow_ticks > sink_tickschooses whichever option survives strictly longer. - Tight openings (
gap_top - gap_bottom = 5.0for a3.0-tall hitbox): Centerymust stay strictly inside a2.0-unit open interval across multiple ticks ((34.5, 36.5)for33..38), which our exact rollout threads along the+10.0, +10.5, +10.5crest of a ballast arc. - Arbitrary float inputs: Rounding
yandvyto6decimal places in thememokey merges equivalent floating-point states cleanly.
Common mistakes
- Re-running boolean survival searches in a countdown loop (
for h in range(HORIZON, 0, -1)) when doomed: Rebuilding a visited set30times multiplies doomed-state latency by30x; memoizing integermax_ticks_survivedhandles both full survival and crash delay in a single pass. - Chasing gap midpoints instead of defaulting to
sink: Because upward lift is instant (+3.0) while downward speed builds slowly (-0.5/tick), hovering near gap midpoints traps the vessel when a deep window follows. - Reusing
memoacross consecutive ticks:ticks_leftcorresponds tostate.x + (HORIZON - ticks_left) * SPEED; carryingmemoto the next tick shifts every cached reef boundary bySPEED = 2.0. - Returning
Noneor raising an exception when doomed: The simulation loop expects aboolon every tick until impact. - Testing on physically unsolvable hand-built channels: Lowering a
5-tall opening by just1unit (32..37fromy = 25, vy = 0) makes it impossible for any controller; always validate test channels with a reachability oracle first.
Alternative approaches
- Forward breadth-first reachable sets: Advance the set of survivable
(y, vy)pairs from tick1toHORIZON, tagging each pair with the tick-1 choice (FalseorTrue) that reaches it. Iterative and simple, though slower on easy ticks because it expands all reachable states rather than stopping on the first30-tick trajectory. - Full-channel backward dynamic programming: When every reef is known at tick
0, sweep backward from the final reef once to mark viable(tick, y, vy)states, turning onlineshould_surfacecalls intoO(1)lookups. - Safety-shielded heuristic policy: Propose actions with a lightweight target-depth rule and use
max_ticks_survivedas an override filter whenever the proposal loses survivability.
Follow-up questions
- If the planning window grew to hundreds of ticks, how could you keep per-tick latency low using state deduplication, kinematic pruning, or A* search? Deduplicating
(ticks_left, y, vy)states via memoization already collapses2^Hbranching into a polynomialO(H^2 * Y)grid. For multi-hundred-tick horizons, combine two extra speedups: first, propagate upcoming reef windows[gap_bottom + r, gap_top - r]backward using maximum climb rate+BALLAST_VYand maximum sink envelopes to prune unreachable(x, y)regions inO(1); second, replace depth-first ordering with A* search (a best-first graph search that expands states minimizing steps taken plus heuristic cost-to-go) guided by farthestxreached and distance to the next safe corridor so a viable trajectory is found nearly linearly. - Suppose the upward ballast velocity and downward drift rate were not provided up front; how would your controller learn them from observed state transitions? Because
SubStatesuppliesvyon every tick, one non-ballast transition directly revealsSINK_RATE = prev_vy - state.vyand one ballast transition revealsBALLAST_VY = state.vy. Under noisy measurements, smooth both estimates online with running averages or least squares (fitting parameters that minimize summed squared velocity prediction errors). SinceBALLAST_VYremains unknown before the first ballast action, trigger one safe exploratory pulse in open water on tick1and temporarily inflateSUB_RADIUSwith a safety buffer until the estimates converge. - Beyond a few manually constructed scenarios, how would you systematically test that your controller generalizes across unseen reef layouts? Build a parameterized procedural generator sampling wide ranges of reef widths, horizontal gaps, opening heights, and alternating shallow/deep jumps, and gate every generated course through an exact brute-force reachability oracle (
_brute_feasible) so pass rates are measured strictly on physically solvable channels. Pair random fuzzing with targeted boundary suites (steepest feasible dives,5-tall openings near both floor and surface, doomed walls), tuneHORIZONon development seeds, and verify zero-shot pass rate on held-out random seeds. - How would the planning state and search complexity change if the submarine could also throttle its horizontal speed on each tick? Varying forward speed lets the vessel slow down to buy extra ticks before steep climbs or dives, expanding the set of physically passable channels while multiplying the per-tick branching factor (the number of action combinations per tick, such as
2ballast choices times3throttle settings =6). Most importantly, horizontal positionxis no longer uniquely determined byticks_left, sox(plus horizontal speedvx, if throttle changes have inertia) must be included explicitly in the memoization key(ticks_left, x, y, vx, vy).
Follow-up questions
- If the planning window grew to hundreds of ticks, how could you keep per-tick latency low using state deduplication, kinematic pruning, or A* search?
- Suppose the upward ballast velocity and downward drift rate were not provided up front; how would your controller learn them from observed state transitions?
- Beyond a few manually constructed scenarios, how would you systematically test that your controller generalizes across unseen reef layouts?
- How would the planning state and search complexity change if the submarine could also throttle its horizontal speed on each tick?
Similar questions
- Lookahead Autopilot for Canyon Gates
- Side-Scrolling Bird Autopilot Across Variable Pipe Layouts
- 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