DataBuffer Fixed Buffer Init

#include <iostream>
using namespace std;

class DataBuffer {
private:
    int size;           // Effective buffer size (1-20)
    int buffer[20];     // Fixed internal storage
    int writeIndex;     // Next write position

public:
    // Constructor: Clamps size and initializes memory
    DataBuffer(int s) {
        // 1. Clamp the size between 1 and 20
        if (s < 1) {
            size = 1;
        } else if (s > 20) {
            size = 20;
        } else {
            size = s;
        }

        // 2. Initialize all 20 elements to 0 (Deterministic startup)
        for (int i = 0; i < 20; i++) {
            buffer[i] = 0;
        }

        // 3. Set the initial write position
        writeIndex = 0;
    }

    // Adds a value if space is available
    void push(int v) {
        // Only store if we haven't reached the effective size limit
        if (writeIndex < size) {
            buffer[writeIndex] = v;
            writeIndex++;
        }
        // If full, the value is ignored as per requirements
    }

    // Prints all values currently stored in the buffer
    void print() {
        for (int i = 0; i < writeIndex; i++) {
            cout << buffer[i] << (i == writeIndex - 1 ? "" : " ");
        }
        // If the buffer is empty, writeIndex is 0 and the loop won't run.
    }
};

int main() {
    int s, n;
    // Read requested buffer size and number of elements to push
    if (!(cin >> s >> n)) return 0;

    DataBuffer buf(s);

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        buf.push(x);
    }

    buf.print();
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

5 7 1 2 3 4 5 6 7

Expected Output

1 2 3 4 5