Skip to content
BytePatterns

Coin Vending Machine

EasyLow-Level Design#class-design#state-machine~15m

Problem

Design a vending machine class. It is built with a price per slot code and a stock count per slot, and it keeps the credit inserted so far. insert(coin) accepts only 5, 10, 25 and 100 and answers "credit N", or "rejected N" for any other coin, which drops straight back out. select(code) answers "sold out" for an empty slot, "need N" when the credit is N short, and otherwise vends, returns the change and resets the credit: "vend CODE, change N". cancel() returns the whole credit as "refund N". The machine must never vend without payment or keep money after a vend or a cancel.

Examples

Input:  prices = A1 65, B2 40; stock = A1 1, B2 0
        insert(25), insert(3), select("A1")
Output: ['credit 25', 'rejected 3', 'need 40']
Input:  then insert(100), select("A1"), select("A1")
Output: ['credit 125', 'vend A1, change 60', 'sold out']
Why:    the only A1 is gone after the first vend
Input:  then select("B2"), insert(10), cancel()
Output: ['sold out', 'credit 10', 'refund 10']
Why:    edge case, a slot that starts empty never takes money for itself

Hints

0 / 3

Stuck on the idea rather than the code? Vending Machine covers it.