SDE Path

Vending Machine (State Pattern)

Medium

Vending Machine (State Pattern)

Coins in, snacks out, change back — a compact state machine that is the canonical showcase for the State pattern.

Requirements

  • Money is integer cents; the machine holds one running balance for the current customer.
  • A failed select (out of stock / insufficient funds) must not lose the balance — the customer can add coins and retry, or refund.
  • A successful purchase consumes the price and returns the entire remainder as change (balance goes to 0).
  • Restocking a slot (add_item) overwrites name, price, and quantity.

API to implement

Implement the class VendingMachine. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.

| Command | Returns | Behavior | |---|---|---| | add_item <slot> <name> <price> <qty> | — | Stock slot slot with qty units of name at price (cents). Replaces any previous item in that slot. | | insert <amount> | int | Insert money; return the new balance. | | select <slot> | string | Try to buy from slot. Unknown slot or zero stock → OUT_OF_STOCK (balance kept). Balance below price → NEED <shortfall> (balance kept). Otherwise dispense: decrement stock, return all remaining balance as change, and answer DISPENSED <name> <change>. | | refund | int | Return the current balance to the customer and reset it to 0. | | stock <slot> | int | Units remaining in slot (0 for unknown slots). |

Input format

The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.

Output format

For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.

This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.

Sample cases

Example 1
Input
10
add_item A1 cola 150 2
insert 100
select A1
insert 100
select A1
stock A1
insert 200
select A1
select A1
refund
Expected output
100
NEED 50
200
DISPENSED cola 50
1
200
DISPENSED cola 50
OUT_OF_STOCK
0
Example 2
Input
4
insert 50
select B2
refund
refund
Expected output
50
OUT_OF_STOCK
50
0