RosettaCodeData/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d

24 lines
619 B
D
Raw Permalink Normal View History

2013-04-10 16:57:12 -07:00
import std.stdio, std.traits, std.algorithm;
2015-02-20 00:35:01 -05:00
auto sma(T, int period)() pure nothrow @safe {
2014-04-02 16:56:35 +00:00
T[period] data = 0;
2013-04-10 16:57:12 -07:00
T sum = 0;
2014-04-02 16:56:35 +00:00
int index, nFilled;
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
return (in T v) nothrow @safe @nogc {
2013-04-10 16:57:12 -07:00
sum += -data[index] + v;
data[index] = v;
index = (index + 1) % period;
2014-04-02 16:56:35 +00:00
nFilled = min(period, nFilled + 1);
return CommonType!(T, float)(sum) / nFilled;
2013-04-10 16:57:12 -07:00
};
}
void main() {
2014-04-02 16:56:35 +00:00
immutable s3 = sma!(int, 3);
immutable s5 = sma!(double, 5);
2013-04-10 16:57:12 -07:00
2014-04-02 16:56:35 +00:00
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
2015-02-20 00:35:01 -05:00
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
2013-04-10 16:57:12 -07:00
}