Project — build a fair checkout queue
Combine a queue for customers with a lookup table for stock. Check stock before recording a sale so an unavailable item never produces a receipt.
Simple example
Two customers each request the same item. One is in stock. Print 1 for the first accepted order and 0 for the second.
def orders = [0, 0]
def stock = [1]
def front = 0
while (front < 2) {
def item = orders[front]
front += 1
if (stock[item] > 0) {
stock[item] -= 1
println(1)
} else {
println(0)
}
}
1 0
Everyday examples
Serve the next customer
Tickets 41 and 18 arrive in that order. Both want the last notebook. Who receives it?
Take the front ticket first. Only after the sale succeeds should stock change from one to zero.
Refuse an unavailable item
A basket requests three apples but stock is two. What remains after declining the whole request?
Check the requested quantity before writing any change. The two apples remain available.
Undo the latest completed sale
Successful orders 41 and 52 are recorded in order. Which receipt is needed to undo only the latest sale?
Keep completed receipts on a stack. Pop receipt 52 and restore only the quantities listed on that receipt.
Cost and limits
Queue order answers who goes next. A stock lookup answers whether the order can proceed. A failed check should leave stock unchanged.