Queues: First Come, First Served
A queue is the opposite of a stack: things join at the back and leave from the front. The first in is the first out (FIFO). Print jobs, customers at a counter, and in the next lesson the cells still to explore in a search: all of them are queues.
A slice as a queue
The simplest queue is a slice too. Add with append, take from index 0:
queue := []string{"soup"}
queue = append(queue, "pizza") // join at the back
front := queue[0] // "soup"
queue = queue[1:] // leave from the front
queue[1:] doesn't copy anything: it moves the start of the slice one place on. The old front values stay in memory until the slice is copied again by append, which is fine for puzzle-sized input.
A ring: a queue with a fixed size
When you know the most values the queue will ever hold, a ring buffer reuses the same array forever. Keep the index of the front (head) and the number of values (size). The back is head + size, and % len(buf) wraps it to the start when it runs off the end:
capacity 4, after pushing 1 2 3, popping 1, pushing 4 5:
buf: [5] [2] [3] [4]
↑ head = 1, size = 4
Nothing is ever moved or copied, so a ring suits a stream that never ends: the last 100 readings, a fixed waiting area, a buffer between two parts of a program.
Taking turns
Queues are also how you share one resource fairly. The front of the queue gets a short turn; if it isn't done, it goes to the back and waits again. Nothing waits forever, and short jobs finish early.
Task
- Complete
PushandPoponRing.Pushreturnsfalseand changes nothing when the ring is full;Popreturnsok == falsewhen it is empty. - Complete
serve(orders []Order, slice int) []Finished. A cook has one stove and cooks the front order for up tosliceminutes. If it needs no more than that, it is ready, and the next order starts straight away. Otherwise it goes to the back of the queue with the minutes it still needs. Return the dishes in the order they are ready, with the minute each was ready (the clock starts at 0). Don't change theordersargument;sliceis at least 1.
This lesson's input starts with the length of a turn, followed by one order per line.