SensorBuffer Fixed Storage

#include <iostream>
using namespace std;

class SensorBuffer {
private:
    int id;          // Sensor identifier
    int data[5];    // Fixed-size buffer for 5 samples
    int count;       // Current number of samples stored

public:
    // Constructor: Initializes the sensor ID and resets the sample count
    SensorBuffer(int sensorId) {
        id = sensorId;
        count = 0;
    }

    // Adds a sample if space is available; otherwise, ignores the input
    void addSample(int v) {
        if (count < 5) {
            data[count] = v;
            count++;
        }
        // If count == 5, the sample is effectively ignored
    }

    // Returns the current number of samples stored in the buffer
    int size() {
        return count;
    }

    // Prints the samples in the order they were added, separated by spaces
    void print() {
        for (int i = 0; i < count; i++) {
            cout << data[i] << (i == count - 1 ? "" : " ");
        }
        // If count is 0, the loop doesn't run and nothing is printed
    }
};

int main() {
    int id, n;
    // Read the sensor ID and the number of incoming samples
    if (!(cin >> id >> n)) return 0;

    SensorBuffer buf(id);

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

    buf.print();
    return 0;
}

Solving Approach

 

 

 


 

Upvote
Downvote
Loading...

Input

42 7 10 20 30 40 50 60 70

Expected Output

10 20 30 40 50