Circular Buffer Indexing

#include <iostream>

class AudioBuffer {
private:
    // Đóng gói biến để tránh can thiệp trực tiếp từ bên ngoài
    int head_index;
    const int SIZE = 8; // Kích thước cố định của bộ đệm

public:
    AudioBuffer() : head_index(0) {}

    // Phương thức tiến bước an toàn (Circular Logic)
    void advance(int steps) {
        if (steps < 0) return; // Bảo vệ chống lại bước âm nếu cần
        
        // Công thức xoay vòng: (vị trí cũ + bước mới) % kích thước
        head_index = (head_index + steps) % SIZE;
    }

    // Getter chỉ đọc
    int getHeadIndex() 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;
        if (!(std::cin >> steps)) break;

        // Gọi API an toàn thay vì cộng trực tiếp
        buffer.advance(steps);

        // Truy cập thông qua getter
        std::cout << "Head: " << buffer.getHeadIndex() << std::endl;
    }

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 5 4 10

Expected Output

Head: 5 Head: 1 Head: 3