Circular Buffer Indexing

#include <iostream>

class AudioBuffer {
private:
    int head_index;
public:
    // TODO: This member is exposed and unsafe. Encapsulate it.
    // TODO: Ensure it wraps around 8 (Size = 8).

    AudioBuffer() : head_index(0) {}

    // TODO: Add a method to advance the index safely.
    void advanceHead(int steps) {
        head_index = (head_index + steps) % 8;
    }
    // TODO: Add a getter for printing.
    int getHead() {
        return head_index;
    }
};

int main() {
    int N;
    if (!(std::cin >> N)) return 0;

    AudioBuffer buffer;

    for (int i = 0; i < N; ++i) {
        int steps;
        std::cin >> steps;

        // TODO: Replace unsafe direct addition
        // buffer.head_index += steps; // This bugs out if index >= 8
        buffer.advanceHead(steps);

        // Output current state (this might be wrong if not fixed)
        std::cout << "Head: " << buffer.getHead() << std::endl;
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 5 4 10

Expected Output

Head: 5 Head: 1 Head: 3