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

PowerBank racks and cells

hard 3 levels ~75 min Optiver

Level 1 Racks, cells and charge states

A power bank has racks numbered 1..k from front to back. Rack i holds at most capacities[i-1] cells. Implement PowerBank(capacities: list[int]).

Each cell has a string id and is loaded at an integer time load with an integer duration >= 1. At time t a cell is:

  • charged if t < load + duration
  • depleted if load + duration <= t < load + 2 * duration
  • spent if t >= load + 2 * duration. Spent cells vanish from the bank and free their slot.

A cell's charge at time t is load + duration - t (it can be negative). Cells are ranked by charge, highest first, and ties go to the lexicographically smaller id. "Most charged" means first in this ranking, and "least charged" means last.

Every method takes a timestamp. Timestamps never decrease from one call to the next. Each method first removes every spent cell, then does its work.

Methods:

  • load_cell(cell_id: str, timestamp: int, duration: int) -> bool: put the cell in the first rack, front to back, that has a free slot, and return True. Return False (and change nothing) if every rack is full or a cell with that id is already in the bank.
  • rack_cells(timestamp: int, rack: int) -> list[str]: the cells in that rack (1-based) in rank order, each formatted "<id>:<state>" (charged or depleted). Return [] for a rack number that doesn't exist.
bank = PowerBank([2, 1])
bank.load_cell("a", 0, 10)   # True, rack 1
bank.load_cell("b", 1, 3)    # True, rack 1
bank.load_cell("c", 2, 4)    # True, rack 2
bank.load_cell("d", 2, 4)    # False, all full
bank.rack_cells(5, 1)        # ["a:charged", "b:depleted"]   charges 5 and -1
bank.rack_cells(7, 1)        # ["a:charged"]                  b is spent at 1 + 2*3 = 7
bank.load_cell("d", 7, 4)    # True, into the slot b freed

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