Circular buffers
A circular buffer reuses a fixed number of slots by wrapping its position back to the start. The program chooses what happens when it fills.
Simple example
Keep only the newest three readings. When 8 arrives, overwrite 2 and print the readings from oldest to newest.
readings = [2, 4, 6]
oldest = 0
readings[oldest] = 8
oldest = (oldest + 1) % 3
step = 0
while step < 3
puts readings[(oldest + step) % 3]
step += 1
end
4 6 8
Everyday examples
Keep the last three readings
A thermometer has saved 18, 19 and 20. It measures 22. Which readings remain in time order?
Overwrite the oldest slot and advance the oldest position. The new reading appears last in time order.
Keep recent photos
A door camera keeps two snapshots. Images 7 and 8 are saved, then image 9 arrives. Which image expires?
Image 7 is the oldest. Reuse its slot for image 9 while retaining image 8.
Protect unserved tickets
A three-slot kiosk buffer is full with tickets 4, 5 and 6. Its policy rejects new tickets while full. What happens to ticket 7?
Leave the stored tickets unchanged and tell the new arrival to wait. Overwriting a waiting customer would lose their turn.
Cost and limits
Track the number of stored items or a full flag so full and empty are distinguishable. Some buffers reject new items instead of overwriting old ones.