#include <stdio.h>
/*
Implement circular buffer insert function
Reqs:
- Insert value at the current head index in the buffer
- Advance head with wrap-around using modulo
- Increment count after insertion
- If buffer is full (count == capacity) -> don't insert anything
User inputs
n -> capacity of buffer
k -> length of array with elements to insert
Plan:
- check if the buffer is full then don't insert anything
- if not full then insert and increment head, tail and count
*/
typedef struct {
int buffer[100];
int head;
int tail;
int count;
int capacity;
} CircularBuffer;
void insert_circular(CircularBuffer *cb, int value) {
// Your logic using only pointer access
if(cb->count == cb->capacity) return;
// If space left in the buffer then insert value
// Get the index of the head
int indexToInsert = (cb->head) % cb->capacity;
cb->buffer[indexToInsert] = value;
cb->head++;
cb->tail++;
cb->count++;
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
CircularBuffer cb = { .head = 0, .tail = 0, .count = 0, .capacity = n };
for (int i = 0; i < k; i++) {
int val;
scanf("%d", &val);
insert_circular(&cb, val);
}
for (int i = 0; i < cb.count; i++) {
printf("%d", cb.buffer[i]);
if(i < cb.count-1){
printf(" ");
}
}
return 0;
}
Input
5 5 10 20 30 40 50
Expected Output
10 20 30 40 50