Lesson contents

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.

Start2 / 1
Result1 0
main.rs
fn main() {
    let orders: [i64; 2] = [0, 0];
    let mut stock: [i64; 1] = [1];
    let mut front: i64 = 0;
    while front < 2 {
        let item: i64 = orders[(front) as usize];
        front += 1;
        if stock[(item) as usize] > 0 {
            stock[(item) as usize] -= 1;
            println!("{}", 1);
        } else {
            println!("{}", 0);
        }
    }
}
Output
1
0
Advertisements

Everyday examples

Serve the next customer

Tickets 41 and 18 arrive in that order. Both want the last notebook. Who receives it?

Start41 18 / 1
Result41

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?

Start2−3?
Result2

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?

Start41 52
Result52

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.