AlgoViz

Design a vending machine

medium 90 min

Build a vending machine around its money: coins in escrow, change from a limited box, stock by place, a slow motor that can jam, and several events that arrive at once.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

See it run

Coins, pieces and three slow seconds: watch who owns each coin after every line.

Operations

A sale with change

Juice for 70, paid with a dollar. The box has one quarter and four dimes.

Step 1 of 7

Press C1

customercallermotorMotormachineVendingMachineescrow100busynoboxCoinBox2511041000inventoryInventoryC12buy(C1)

A dollar lies in escrow. It is still the customer's.

Step 1: Press C1

def buy(self, code):    with self._lock:        if self._busy:            raise Busy()        product = self._inventory.find(code)        extra = sum(self._escrow) - product.cents        if extra < 0:            raise NotEnough(-extra)        change = self._box.plan(extra, self._escrow)        if change is None:            raise NoChange(extra)        self._inventory.claim(code)        self._busy = True    try:        self._motor.drop(code)    except Jammed:        with self._lock:            self._inventory.put_back(code)            self._busy = False        raise    with self._lock:        self._box.settle(self._escrow, change)        self._escrow = []        self._busy = False    return Sale(product, tuple(change))
Cost
The motor
Guarantee
Money or product

Plan before claim, claim before drop, coins last.

In the real world

The same vending machine doing real jobs. Pick one and step through it.

Insert twice, choose, get 50 back.

Step 1 of 6

Waiting

customercallermotorMotormachineVendingMachineescrownonebusynoboxCoinBox2521031000inventoryInventoryA1 Cola5

Escrow is empty: idle.

Step 1: Waiting

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Money as a float

    critical

    Ten times 0.1 is less than 1. A fair customer is refused.

    Wrong
    balance += 0.10
    Right
    escrow.append(Coin.DIME)      # whole cents
  • Change after the product

    critical

    The juice is out and the change does not exist.

    Wrong
    motor.drop(code)change = box.plan(extra, escrow)
    Right
    change = box.plan(extra, escrow)if change is None: raise NoChange(extra)motor.drop(code)
  • A lock around the motor

    critical

    Everybody waits for three seconds, and the second press is queued.

    Wrong
    with self._lock:    ...    self._motor.drop(code)
    Right
    with self._lock:    ...    self._busy = Trueself._motor.drop(code)
  • Taking the coins first

    major

    After a jam or a crash the refund needs change again, and may fail.

    Wrong
    box.add(escrow); escrow = []motor.drop(code)
    Right
    motor.drop(code)box.settle(escrow, change)
  • Greedy over a limited box

    major

    It refuses sales that are possible.

    Wrong
    for coin in sorted(stock, reverse=True): ...
    Right
    best = {0: []}      # search all sums
  • Catching every error as a jam

    major

    A timeout is not a jam. The juice may have fallen.

    Wrong
    except Exception:    put_back(code)
    Right
    except Jammed:    put_back(code)

Interview tips

  • Open with

    • Where is each coin?
    • Escrow, box, customer.
    • Refuse before anything moves.
  • Reject aloud

    • A balance without coins.
    • A class for each mood, for now.
    • A global machine.
  • Prove it

    • Count all coins after each step.
    • Stop the motor, press again.
    • Cut the journal after each line.
  • Never

    • Print the change.
    • Charge before the drop.
    • Read busy as sold out.