Skip to content

Instantly share code, notes, and snippets.

@squarewave
Created August 30, 2014 17:48
Show Gist options
  • Save squarewave/cffcd72971a00dc9f1c2 to your computer and use it in GitHub Desktop.
Save squarewave/cffcd72971a00dc9f1c2 to your computer and use it in GitHub Desktop.
namespace rollingaveragernamespace {
RollingAverager::RollingAverager() {
this.buffer_index_ = 0;
this.buffer_ = {0};
this.sum = 0;
}
long RollingAverager::Roll(long next_input) {
++this.buffer_index_;
this.buffer_index_ &= (kBufferSize - 1);
this.sum += next_input;
this.sum -= this.buffer_[this.buffer_index_];
this.buffer_[this.buffer_index_] = next_input;
return this.sum / kBufferSize;
}
}
#ifndef PROJECT_PATH_ROLLING_AVERAGER_H_
#define PROJECT_PATH_ROLLING_AVERAGER_H_
namespace rollingaveragernamespace {
class RollingAverager {
private:
const char kBufferSize = 8;
char buffer_index_;
long buffer_[kBufferSize];
long sum;
public:
RollingAverager();
long Roll(long next_input);
};
} // namespace rollingaveragernamespace
#endif // PROJECT_PATH_ROLLING_AVERAGER_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment