Lesson contents

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.

Start2 4 6
Result4 6 8
Lesson.R
readings <- c(2, 4, 6)
oldest <- 0
readings[(oldest) + 1] <- 8
oldest <- (oldest + 1) %% 3
step <- 0
while (step < 3) {
    cat(readings[((oldest + step) %% 3) + 1], "\n", sep = "")
    step <- step + 1
}
Output
4
6
8
Advertisements

Everyday examples

Keep the last three readings

A thermometer has saved 18, 19 and 20. It measures 22. Which readings remain in time order?

Start18 19 20
Result19 20 22

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?

Start7 8 9
Result7

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?

Start4 5 6
Result4 5 6

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.