data-structures · beginner · ~15 min
Use modular arithmetic for wrap-around indexing.
Compute a wrapped index into a ring buffer.
A queue backed by a ring buffer of capacity cap wraps around at the end. Implement int ring_index(int start, int k, int cap) that returns the buffer index k positions after start, wrapping past the end of the buffer.
start: a valid starting index, 0 <= start < cap.k: a non-negative offset (k >= 0), possibly larger than cap.cap: the buffer capacity (cap > 0).int: the index k steps after start, wrapped into [0, cap).
ring_index(2, 1, 8) -> 3 (no wrap)
ring_index(6, 4, 8) -> 2 (wraps past the end)
ring_index(3, 5, 8) -> 0 (lands exactly on 0)
start.cap wrap around.start (0 <= start < cap), k (>= 0), cap (> 0).
int: index k positions after start, wrapped into [0, cap).
Use modulo cap for the wrap-around.
int ring_index(int start, int k, int cap) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.