AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Watch lesson4:48

Extending it

Electric, accessible, passes, valet

The point: a good extension adds a class or a value and edits little. For each one, say which class changes, and prove that the others do not.

Features

From a size to a need

Electric cars need a charger. Some drivers need an accessible space. Tall vans need height. With subclasses this gives LargeElectricAccessibleSpot. With features it is a set: a space has some, an arrival needs some.

Python
from dataclasses import dataclass@dataclass(frozen=True)class Spot:    id: str    size: int    features: frozenset[str] = frozenset()@dataclass(frozen=True)class Need:    """What one arrival asks for. Vehicle type is only the starting point."""    min_size: int    must_have: frozenset[str] = frozenset()RESERVED_FOR = {"accessible"}          # only people who need it may use itdef fits(spot: Spot, need: Need) -> bool:    return (spot.size >= need.min_size            and need.must_have <= spot.features            and (spot.features & RESERVED_FOR) <= need.must_have)def waste(spot: Spot, need: Need) -> tuple[int, int]:    """Smaller is better: do not spend a large space or a charger on someone who does not need it."""    return (spot.size - need.min_size, len(spot.features - need.must_have))def choose(free: list[Spot], need: Need) -> Spot | None:    return min((s for s in free if fits(s, need)), key=lambda s: waste(s, need), default=None)free = [Spot("E1", 2, frozenset({"charger"})), Spot("M1", 2), Spot("A1", 2, frozenset({"accessible"})), Spot("L1", 3)]print(choose(free, Need(2)).id,      choose(free, Need(2, frozenset({"charger"}))).id,      choose(free, Need(2, frozenset({"accessible"}))).id,      choose(free, Need(3)).id)
fits says what is allowed, waste says what is wise. A car without a need gets M1 although E1 would fit, and it may never use A1. The bus gets L1.
Edit and run it in your browser
RuleLine
Large enoughspot.size >= need.min_size
Has what I needneed.must_have <= spot.features, subset
Not kept for somebody elsereserved features of the space must be among my needs
Do not waste large or special spacesmin by size difference, then by unused features
With few combinations keep a queue for each pair of size and features, in order of waste. The scan is for explaining.

What changes

Eight follow-ups, and the blast radius

Follow-upNewEditedUntouched
Truck as a vehicleOne enum lineNothingEverything else
Electric spacesNeed, featuresSpotPool.claimPricing, payment, tickets
Accessible spacesOne reserved featureNothing morePool logic
Monthly passesMonthlyPass ruleComposition in mainParkingLot
Bus over five spacesA run pool for the large rowTicket holds several spacesPricing interface
ValetA queue of keys, a job for each carEnter at the deskPool
Several car parksGarage with a map of lotsNothing inside a lotAll of ParkingLot
Plate camera instead of paperLookup by plateGatesLot

Passes

Monthly passes as a price

Python
class MonthlyPass:    """A pricing rule around another rule. The lot does not know that passes exist."""    def __init__(self, valid, inner) -> None:        self._valid, self._inner = valid, inner       # valid(plate, when) -> bool    def price_cents(self, stay, left_at) -> int:        if self._valid(stay.plate, stay.entered_at):            return 0        return self._inner.price_cents(stay, left_at)
A pass is a rule that says zero, wrapped around the ordinary rule. The stay here carries the plate. valid is a function, so a test can pass a lambda.

Electric cars need a charger. Where does that go?

BreaksElectricCar extends Car, ElectricSpot extends Spot
How
Two more subclasses, and instanceof in the pool.
Limit
The next feature doubles the trees. An electric car that does not want to charge does not fit.
Choose when
Never for a property that can be combined.
WorksA boolean on the space
How
has_charger.
Limit
Fine once. The third boolean is the sign to change.
Choose when
One feature, sure to stay the only one.
StrongA need and a set of features
How
The arrival says what it must have, the pool matches and wastes little.
Limit
The claim rule becomes a real algorithm, and needs tests.
Choose when
Two or more features.

Charging

Two meters, one ticket

  1. 1

    The charger is not a space

    It has its own states: idle, charging, done, broken. Spot remains a record.

  2. 2

    It is billed by energy

    Whole watt hours times a whole price per kilowatt hour, divided once at the end. A second line on the same receipt.

  3. 3

    Blocking

    Full battery, car still there: an idle fee after 30 minutes. That is a pricing rule with another start time.

  4. 4

    Broken

    Take the feature away from the space, not the space from the lot.