87. Peek N Bytes from Circular Buffer

Back To All Submissions
Previous Submission
Next Submission

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) {
    // Your code here
    int peeked[n];
    bool passed = false;
    for (size_t i=0; i<n; i++){
        int pos = ((*cb).tail + i) % (*cb).capacity;
        if (((*cb).count - i) <= 0 | passed) {
            peeked[i] = -1;
            passed = true;
        } else {
            peeked[i] = (*cb).buffer[pos];
        }
    }
    char msg[255];
    sprintf(msg, "%d", peeked[0]);
    for (size_t i=1; i<n; i++){
        int val = peeked[i];
        if (val == -1) {
            sprintf(msg, "%s NULL", msg);
        } else {
            sprintf(msg, "%s %d", msg, val);
        }
    }
    printf(msg);
}

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

 

 

 

Was this helpful?
Upvote
Downvote