~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

Squirrel nut storage tracker

medium 3 levels ~55 min Optiver

Level 1 Cone-shaped hiding spots

A researcher tracks where squirrels hide nuts. Implement SquirrelResearch(locations: dict[str, int]), where locations maps a location id to its number of levels (at least 1).

Each location is a cone. Level 0 is the deepest (narrowest) level, and each level above it is wider. Capacities follow the Fibonacci numbers 1, 2, 3, 5, 8, 13, ..., deepest first. So a 3-level location holds 1 + 2 + 3 = 6 nuts, and a 4-level one holds 11.

  • hide_nut(timestamp: int, location_id: str, nut_id: str, weight: int, time_to_expire: int) -> bool: store the nut in the deepest level that still has room, and return True. Return False and change nothing if the location doesn't exist, if it is full, or if a nut with this id is already stored anywhere (in any location). Keep timestamp and time_to_expire, which level 3 will use.
  • level_contents(location_id: str) -> list[list[str]]: one list per level, deepest level first. Each list gives that level's nut ids, heaviest first, with ties going to the lexicographically smaller id. Return [] for an unknown location.
s = SquirrelResearch({"oak": 3, "elm": 1})
s.hide_nut(0, "oak", "n1", 5, 100)   # True  -> level 0
s.hide_nut(1, "oak", "n2", 9, 100)   # True  -> level 1
s.hide_nut(2, "oak", "n3", 1, 100)   # True  -> level 1
s.hide_nut(3, "elm", "n3", 4, 100)   # False: n3 is already hidden
s.hide_nut(4, "pine", "n9", 4, 100)  # False: no such location
s.level_contents("oak")              # [["n1"], ["n2", "n3"], []]

Timestamps are integers and never decrease from one call to the next.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc