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.
    // TODO: Add a getter for printing.
    void update_head(int steps){
        head_index = (head_index + steps)%8;
    }

    int get_head(void) const{
        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.head_index += steps; 
        buffer.update_head(steps);

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

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 5 4 10

Expected Output

Head: 5 Head: 1 Head: 3