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

Verify

Trace it with real values

The point: do not say "done". Put five vehicles through your code, line by line, and write the state after each call.

Trace

The seaside day

Start: S1, M1, M2, M3, L1. Rates 100, 200, 500 cents an hour

CallClaimSmallMediumLargeActiveReturns
startS1M1 M2 M3L1none
09:00 enter RED-1, carstarts at mediumS1M2 M3L11ticket 1, M1
09:00 enter MOTO-1smallemptyM2 M3L11 2ticket 2, S1
09:00 enter BUS-1largeemptyM2 M3empty1 2 3ticket 3, L1
09:00 enter MOTO-2small empty, mediumemptyM3empty1 2 3 4ticket 4, M2
09:00 enter BUS-2large emptyemptyM3empty1 2 3 4nothing
09:05 enter BLUE-1, carmediumemptyemptyempty1 to 5ticket 5, M3
09:06 enter GREEN-1, carnothing leftemptyemptyempty1 to 5nothing
11:10 leave 1emptyM1empty2 to 5600 cents
11:11 enter GREEN-1, carmediumemptyemptyempty2 to 6ticket 6, M1
BUS-2 and GREEN-1 got nothing and used no number: the next ticket after 5 is 6. After each row, free plus active is 5.

Edges

Small inputs that break large designs

InputExpectedWhere it is decided
Leave in the same second1 hour, 200 centsmax(1, ...)
Leave after exactly 60 minutes1 hour(3600 + 3599) // 3600 = 1
Leave after 60 minutes and 1 second2 hours(3601 + 3599) // 3600 = 2
Leave with ticket 1 againUnknownTicketpop returned nothing
Enter RED-1 while it is insideAlreadyInsideinside
Card declined, then paidFirst an error, then a receipt, one chargeexcept puts the ticket back
Enter RED-1 after it leftA new ticketinside.discard
A lot without spacesNothing for everybodyThree empty queues
Python
first = lot.enter(Vehicle("A", VehicleType.CAR))cards.declines = 1try:    lot.leave(first.id)except PaymentDeclined:    passbefore = lot.free()[SpotSize.MEDIUM]        # still taken: not released before paymentreceipt = lot.leave(first.id)               # the ticket was put back, so this worksassert lot.free()[SpotSize.MEDIUM] == before + 1assert cards.charged[f"ticket-{first.id}"] == receipt.cents == 200
The same edges as a test you could write in the last five minutes. Add it after the code above.

Invariants

Four sentences that are true after every call

  1. 1

    Nothing is lost

    Free spaces plus spaces on tickets is the number of spaces. (During a payment the ticket is in the hands of leave.)

  2. 2

    Nothing is doubled

    No two active tickets name the same space or the same plate.

  3. 3

    It fits

    On every ticket, the size of the space is at least the smallest size of the vehicle.

  4. 4

    Money and spaces agree

    Every space that came back has exactly one successful charge.

The question to ask at each line of leave