All submissions

Peek N Bytes from Circular Buffer

Code

#include <stdio.h>

typedef struct {
    int buffer[10];
    int head;
    int tail;
    int count;
    int capacity;
} CircularBuffer;

// Write your logic inside this function
void peek_bytes(CircularBuffer *cb, int n) {
    int read_value = 0; // init read value
    int it=cb->tail; // init buffer index
    int step = 0;// init step counter
    int max_step = cb->count;
    int valid_step=0;

    while (step<n)
    {

        // read value from buffer
        read_value = cb->buffer[it];

        if (step>=max_step) {
            printf("NULL ");
        }

        else {
            printf("%d ",read_value);
            valid_step++;
        }


        it = (it+1)%(cb->capacity);
        step++;

        // decrease count after every successful read
        if (cb->count-1 >= 0) {
            cb->count--;
        }


    }

    // advance the tail
    cb->tail = (cb->tail+(valid_step)) % (cb->capacity);
}

int main() {
    CircularBuffer cb = {
        .buffer = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
        .head = 3,
        .tail = 7,
        .count = 6,
        .capacity = 10
    };

    int n;
    scanf("%d", &n);

    peek_bytes(&cb, n);

    return 0;
}

Solving Approach

 

 

 

Loading...

Input

4

Expected Output

80 90 100 10