Sample history by age
Store the last few samples and read them back by how old they are. A medium embedded C problem (Buffers and data structures), run and graded in the browser.
medium · Buffers and data structures · circular-buffer · filters
Digital filters need the last few inputs. Keep the most recent HISTORY_SIZE samples in a circular buffer. A zero-initialised history_t is empty.
history_pushstores a sample, replacing the oldest once the buffer is full.history_get(h, age)returns the sample pushedagepushes ago: age 0 is the newest, age 1 the one before it. If fewer thanage + 1samples are stored, return 0.
Starter code
void history_push(history_t *h, int16_t v) {
}
int16_t history_get(const history_t *h, size_t age) {
// age 0 is the most recent sample.
return 0;
}Example tests
Newest first
history_t h = { 0 };
history_push(&h, 10); history_push(&h, 20); history_push(&h, 30);
printf("%d %d %d\n", history_get(&h, 0), history_get(&h, 1), history_get(&h, 2));Expected output:
30 20 10Older than anything stored
history_t h = { 0 };
printf("%d ", history_get(&h, 0));
history_push(&h, 10);
printf("%d %d\n", history_get(&h, 0), history_get(&h, 1));Expected output:
0 10 0Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.