data-structures · intermediate · ~15 min
Compute occupancy in a circular buffer.
Compute how many items a ring buffer currently holds.
Implement int ring_count(int head, int tail, int cap) that returns the number of items stored between head (the front of the queue) and tail (the next free slot) in a ring buffer, accounting for wrap-around.
head: index of the front item, 0 <= head < cap.tail: index of the next free slot, 0 <= tail < cap.cap: the buffer capacity.int: the number of stored items. In this convention head == tail means the queue is empty.
ring_count(2, 5, 8) -> 3
ring_count(4, 4, 8) -> 0 (empty)
ring_count(6, 2, 8) -> 4 (wraps around)
head and tail means empty (returns 0).tail < head the count wraps around the end of the buffer.head, tail (both in [0, cap)), and cap.
int: number of items between head and tail; equal indices mean empty.
Add cap before the modulo so the result stays non-negative.
int ring_count(int head, int tail, int cap) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.