Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3); m.next(1) = 1 m.next(10) = (1 + 10) / 2 m.next(3) = (1 + 10 + 3) / 3 m.next(5) = (10 + 3 + 5) / 3This one is to use the Deque structure.
#include <queue>
#include <iostream>
using namespace std;
class MovingAverage {
private:
queue<int> q;
int size;
double sum;
public:
MovingAverage(int size) {
this->size = size;
sum = 0;
}
double next(int val) {
if(q.size() >= size) {
sum -= q.front();
q.pop();
}
q.push(val);
sum += val;
return double(sum)/q.size();
}
};
int main(void) {
MovingAverage a(3);
int tmp;
while(cin >> tmp) {
cout << "average: " << a.next(tmp) << endl;
}
}