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

Pricing strategy

Rules that can be swapped and stacked

The point: "several ways to calculate one thing" is the sentence that asks for Strategy. Keep each rule small, and stack them instead of making one class for each combination.

Strategy

Three rules, one question

RuleFor130 minutes, medium
Hourly, every started hourOrdinary days3 x 200 = 600 cents
FlatMatch days, airports by the day1500 cents
Weekend at 1.5 timesSaturday and Sunday600 x 1.5 = 900 cents
First 15 minutes free, then hourlyDropping somebody off600 cents; after 14 minutes 0
At most 2000 cents a dayLong stays600 cents; after 12 hours 2000
Python
from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezone@dataclass(frozen=True)class Stay:    size: str    entered_at: datetimeclass Hourly:    def __init__(self, cents: dict[str, int]) -> None:        self._cents = cents    def price_cents(self, stay: Stay, left_at: datetime) -> int:        seconds = int((left_at - stay.entered_at).total_seconds())        return max(1, (seconds + 3599) // 3600) * self._cents[stay.size]class FirstMinutesFree:    """Wraps another rule: the open/closed principle with two lines."""    def __init__(self, minutes: int, inner) -> None:        self._limit, self._inner = timedelta(minutes=minutes), inner    def price_cents(self, stay: Stay, left_at: datetime) -> int:        if left_at - stay.entered_at <= self._limit:            return 0        return self._inner.price_cents(stay, left_at)class DailyCap:    """No day costs more than the cap. A day is 24 hours from entry."""    def __init__(self, cap_cents: int, inner) -> None:        self._cap, self._inner = cap_cents, inner    def price_cents(self, stay: Stay, left_at: datetime) -> int:        days, rest = divmod(left_at - stay.entered_at, timedelta(days=1))        total = days * self._cap        if rest:            last_day = replace(stay, entered_at=left_at - rest)            total += min(self._cap, self._inner.price_cents(last_day, left_at))        return totalrule = FirstMinutesFree(15, DailyCap(2000, Hourly({"M": 200})))start = datetime(2026, 7, 4, 9, tzinfo=timezone.utc)for hours in (0.25, 2.1667, 12, 24, 49.5):    print(hours, rule.price_cents(Stay("M", start), start + timedelta(hours=hours)))
Strategy for the base rule, Decorator for the two wrappers. 49.5 hours: two full days at 2000, then 1.5 hours, which are two started hours at 200. Together 4400 cents.
Edit and run it in your browser

Mistakes

Five bugs in a fee method

CodeProblemInstead
Duration.between(a, b).toHours()Rounds down: 119 minutes are 1 hourRound up from seconds
3.5 * hourlyRateIs it per hour or per started hour? 3.5 x 400 = 1400, or 4 x 400 = 1600Ask, then write it into the test
double price0.1 + 0.2 is not 0.3Whole cents
price * 1.5 for weekendsA fraction of a cent, and a float(cents * 15000 + 5000) // 10000: basis points, rounded half up
"Is the exit on a weekend?"Friday 23:00 to Saturday 01:00 pays the weekend for allPrice each hour by its own day: next page

Swap

Changing the rule while cars are inside

Marketing changes the price at noon. Who pays what?

BreakssetPricing(newRule) on the running lot
How
A field that any thread may replace.
Limit
Someone who came at 9 for 200 an hour pays 400. Two threads in one leave may use two rules.
Choose when
Never without a lock, and not for people who saw the old sign.
WorksThe rule at exit decides
How
Restart, or an atomic swap, with the new rule.
Limit
Legal in some places, a surprise in all.
Choose when
If the sign says prices at time of exit.
StrongThe tariff at entry decides
How
The ticket carries the tariff id. Tariffs.get(id) returns a rule that never changes; a new price is a new id.
Limit
Old tariffs must be kept while anyone is inside.
Choose when
Nearly always. The price the driver saw is the price they pay.

Test

Why this is easy to test

A rule is a function of its arguments. No clock, no database, no lot. A table of stays and expected cents is the test, and the same table can go to the people who set the prices.

Where the rule comes from

The factory changes, the lot does not.