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:

  1. Velocity update: Returning True sets vy = BALLAST_VY (3.0); returning False sets vy = vy - SINK_RATE (vy - 0.5).
  2. Position update: y becomes y + vy, and x becomes x + SPEED (x + 2.0).
  3. 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_left and x - SUB_RADIUS <= reef.x_right), the hitbox does not sit strictly inside the vertical window (y - SUB_RADIUS <= reef.gap_bottom or y + 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.reefs is sorted in non-decreasing order of x_left, with reef.x_left < reef.x_right and FLOOR_Y < reef.gap_bottom < reef.gap_top < SURFACE_Y.
  • Boundary contact (<= against FLOOR_Y or gap_bottom, >= against SURFACE_Y or gap_top during horizontal overlap) is a crash.
  • should_surface must always return a bool (True or False), use only the Python standard library, and finish well within a few milliseconds per tick even on inescapable states.

Step-by-step walkthrough

  1. 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) sets vy = BALLAST_VY = 3.0; drifting downward (False) subtracts SINK_RATE = 0.5 from vy. Next, y += vy and x += SPEED = 2.0.
    • Collision box: The vessel is a 3 x 3 square (SUB_RADIUS = 1.5). The sea floor sits at FLOOR_Y = 1.0 and the surface sits at SURFACE_Y = 59.0, so center y must remain strictly inside (2.5, 57.5). Contacting any boundary ends the run: overlapping a reef horizontally (x + 1.5 >= reef.x_left and x - 1.5 <= reef.x_right) crashes whenever y - 1.5 <= reef.gap_bottom or y + 1.5 >= reef.gap_top.
    • Visibility & inescapable states: should_surface inspects state.reefs (sorted by x_left) and must always return a bool — 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.5
    

    Climbing starts immediately at full speed (+3.0 on the very first tick), whereas sinking from rest starts at -0.5 and needs several consecutive ticks to build downward speed. That asymmetry guides our entire tie-breaking strategy.

  2. 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, reefs is sorted by x_left: as soon as reef.x_left > x + r, neither this reef nor any subsequent reef can overlap the hitbox, so we break immediately.

    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 False
    
  3. Why reactive rules and 1-tick checks fail

    Trace Example 1: x = 4.0, y = 18.0, vy = -0.5 facing Reef(x_left=13.0, x_right=23.0, gap_bottom=27.5, gap_top=46.0). At SPEED = 2.0, the vessel's hitbox (r = 1.5) reaches x_left = 13.0 on tick 4 (x = 12.0, right edge 13.5 >= 13.0), where center y needs y > 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 reach 29.0. Likewise, a reactive midpoint rule ("vent ballast whenever y is 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).

  4. Why unmemoized lookahead explodes near dead ends

    To plan HORIZON = 30 ticks ahead, naive recursion tries (False, True) at every tick. In open water, the very first all-sink/occasional-blow path reaches 30 ticks immediately.

    Whenever a branch is unescapable, however — such as testing whether sink can clear a steep reef 25 ticks ahead when it physically cannot — unmemoized recursion must exhaust every combination of sinks and blows before proving failure (2^25 to 2^30 branches, stalling a single tick for hundreds of milliseconds). That slowdown strikes right near narrow gaps and walls.

  5. Key idea: memoize maximum ticks survived per state

    Distinct sequences of ballast actions frequently converge on the exact same state: - Within one should_surface call, horizontal position x at ticks_left remaining ticks is always state.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 30 ticks: - ticks_left: 1 .. 29 (< 30 values). - vy after t ticks: either vy_0 - 0.5 * t or 3.0 - 0.5 * k (k ticks since the last blow), at most t + 1 <= 31 values. - Half-integer y strictly inside (2.5, 57.5): at most 109 heights (3.0, 3.5, ..., 57.0).

    That bounds the entire search graph by 30 * 31 * 109 ≈ 101,000 states instead of 2^30 ≈ 1.07 billion branches. Caching integer max_ticks_survived (0 .. ticks_left) in memo and breaking as soon as best == ticks_left achieves two goals at once: 1. On survivable states, the search stops on the first 30-tick trajectory (~50 recursive 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 best
    
  6. Score both choices: prefer sinking and re-plan every tick

    On every call to should_surface(state): 1. Evaluate sink (False) first: When sink_ticks == HORIZON (as in Example 2 at y = 34.0, vy = 0.0), drifting downward preserves a safe 30-tick future, so we immediately return False without searching blow. 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. Evaluate blow (True) sharing memo: Both score_action(state, False, memo) and score_action(state, True, memo) enter max_ticks_survived at ticks_left = HORIZON - 1 (next_x = state.x + SPEED), so sharing one memo dictionary is 100% valid. Returning blow_ticks > sink_ticks picks ballast whenever sinking fails (blow_ticks == HORIZON > sink_ticks) or when doomed and ballast survives strictly longer, and returns False on ties (including 0 == 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_ticks
    
  7. Choose the horizon and trace the hardest reef patterns

    Climbing nearly the entire 55-unit water column at +3.0 per tick takes ~19 ticks, and traversing a 10..12-wide reef takes ~7 ticks, totaling ~26 ticks. Choosing HORIZON = 30 (60 horizontal units) comfortably spans full-column climbs and steep dives in well under 1.5 ms per tick:

    • Example 3 transition — shallow upper window (35..54 at x = 24..32), then deep window (5..23 at x = 56..64): Only 24 horizontal units (12 ticks) separate the two formations, requiring a descent from y > 36.5 down to y < 21.5 while leveling out before gap_bottom = 5. With HORIZON = 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), height 5 for a 3-tall hitbox from y = 25.0, vy = 0.0): Across the 3 ticks overlapping [26, 30], center y must stay strictly inside (34.5, 36.5) — leaving only 35.0, 35.5, 36.0 on the 0.5 grid! 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 by 1 unit (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.
  8. 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):

  1. Test sink (False) first: Sinking on tick 1 moves to (x = 6.0, y = 17.0, vy = -1.0). Even if the vessel vents ballast on ticks 2, 3, 4 (+3.0 each tick), center height reaches 20.0 -> 23.0 -> 26.0 <= 29.0, hitting the lower reef on tick 4 (sink_ticks = 3 < 30).
  2. Test blow (True) next: Venting ballast on ticks 1, 2, 3, 4 climbs 21.0 -> 24.0 -> 27.0 -> 30.0 > 29.0, entering the window cleanly and surviving all 30 ticks (blow_ticks = 30).
  3. Commit and re-plan: should_surface returns True now and runs a fresh search from the updated SubState on the next tick.

Complexity

  • Time per call: O(S * P) in both normal and doomed states. Here S is the number of distinct (ticks_left, rounded_y, rounded_vy) states visited and P is the number of nearby reefs inspected by hits_something before breaking at reef.x_left > x + r. Across HORIZON = 30 ticks, ticks_left takes < 30 values, vy takes at most 31 values, and 0.5-spaced heights inside (2.5, 57.5) take at most 109 values, bounding S by ~101,000 states (versus 2^30 ≈ 1.07 billion raw sequences). Survivable calls exit on the first 30-tick trajectory (~50 states on average), and even inescapable states finish in a single shared-memo pass.
  • Space: O(S + HORIZON). memo holds at most S entries during one should_surface call, and recursion depth never exceeds HORIZON = 30; zero state persists across ticks.

Edge cases

  • Open water (reefs = []): Only FLOOR_Y = 1.0 and SURFACE_Y = 59.0 constrain vertical motion; the vessel drifts downward peacefully, vents ballast right above y = 2.5, and repeats forever.
  • Immediate unavoidable collision (sink_ticks == 0 and blow_ticks == 0): At y = 56.0, vy = 4.0, sinking moves to 59.5 and venting moves to 59.0, both hitting SURFACE_Y = 59.0 (y + 1.5 >= 59.0). blow_ticks > sink_ticks (0 > 0) cleanly returns False.
  • Doomed several ticks ahead: When an unpassable reef lies within the horizon, blow_ticks > sink_ticks chooses whichever option survives strictly longer.
  • Tight openings (gap_top - gap_bottom = 5.0 for a 3.0-tall hitbox): Center y must stay strictly inside a 2.0-unit open interval across multiple ticks ((34.5, 36.5) for 33..38), which our exact rollout threads along the +10.0, +10.5, +10.5 crest of a ballast arc.
  • Arbitrary float inputs: Rounding y and vy to 6 decimal places in the memo key 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 set 30 times multiplies doomed-state latency by 30x; memoizing integer max_ticks_survived handles 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 memo across consecutive ticks: ticks_left corresponds to state.x + (HORIZON - ticks_left) * SPEED; carrying memo to the next tick shifts every cached reef boundary by SPEED = 2.0.
  • Returning None or raising an exception when doomed: The simulation loop expects a bool on every tick until impact.
  • Testing on physically unsolvable hand-built channels: Lowering a 5-tall opening by just 1 unit (32..37 from y = 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 tick 1 to HORIZON, tagging each pair with the tick-1 choice (False or True) that reaches it. Iterative and simple, though slower on easy ticks because it expands all reachable states rather than stopping on the first 30-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 online should_surface calls into O(1) lookups.
  • Safety-shielded heuristic policy: Propose actions with a lightweight target-depth rule and use max_ticks_survived as 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 collapses 2^H branching into a polynomial O(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_VY and maximum sink envelopes to prune unreachable (x, y) regions in O(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 farthest x reached 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 SubState supplies vy on every tick, one non-ballast transition directly reveals SINK_RATE = prev_vy - state.vy and one ballast transition reveals BALLAST_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). Since BALLAST_VY remains unknown before the first ballast action, trigger one safe exploratory pulse in open water on tick 1 and temporarily inflate SUB_RADIUS with 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), tune HORIZON on 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 2 ballast choices times 3 throttle settings = 6). Most importantly, horizontal position x is no longer uniquely determined by ticks_left, so x (plus horizontal speed vx, if throttle changes have inertia) must be included explicitly in the memoization key (ticks_left, x, y, vx, vy).

Follow-up questions

Similar questions

More Aqr interview questions

All 3 Aqr questions →