diff --git a/TakayunAverage.h b/TakayunAverage.h new file mode 100644 index 0000000..8bcd71e --- /dev/null +++ b/TakayunAverage.h @@ -0,0 +1,55 @@ +#pragma once + +#define TAKAYUN_AVERAGE_DEBUG__DISABLE + +#include +using namespace std; + +template +class TakayunAverage { +private: + T sum, *buff, average; + int buff_size, index; + + void initialize(int buff_size) { + this->buff_size = buff_size; + buff = new T[buff_size]; + for (int i = 0; i < buff_size; i++) buff[i] = 0; + index = sum = average = 0; + } + + T update_average(T data) { +#ifdef TAKAYUN_AVERAGE_DEBUG__ENABLE + cout << "[TakayunAverage::update_average]: "; + for (int i = 0; i < buff_size; i++) cout << buff[i] << " "; + cout << endl; +#endif + static T first; + index++; + if (!(index < buff_size)) index = 0; + first = buff[index]; + buff[index] = data; + sum = sum - first + data; + average = sum / buff_size; + return average; + } + +public: + TakayunAverage(int buff_size) { + initialize(buff_size); + } + TakayunAverage(int buff_size, T initial_value) { + initialize(buff_size); + for (int i = 0; i < buff_size; i++) update_average(initial_value); + } + ~TakayunAverage() { + delete[] buff; + } + + T get_average() { + return average; + } + T get_average(T data) { + return update_average(data); + } +}; diff --git a/example1.cpp b/example1.cpp new file mode 100644 index 0000000..8827822 --- /dev/null +++ b/example1.cpp @@ -0,0 +1,15 @@ +//#define TAKAYUN_AVERAGE_DEBUG__ENABLE +#include "TakayunAverage.h" + +int main() { + /* TakayunAverage(int buff_size) + * TakayunAverage(int buff_size, T initial_average_value) + */ + TakayunAverage ca(10); + cout << ca.get_average(1) << endl; + cout << ca.get_average(2) << endl; + cout << ca.get_average(3) << endl; + cout << ca.get_average(4) << endl; + cout << ca.get_average(5) << endl; + return 0; +} diff --git a/example2.cpp b/example2.cpp new file mode 100644 index 0000000..dba82e2 --- /dev/null +++ b/example2.cpp @@ -0,0 +1,11 @@ +#include "TakayunAverage.h" + +int main() { + TakayunAverage *ca = new TakayunAverage(3, 12); + cout << ca->get_average(1) << endl; + cout << ca->get_average(2) << endl; + cout << ca->get_average(3) << endl; + cout << ca->get_average(4) << endl; + cout << ca->get_average(5) << endl; + return 0; +}