Moving average
Very often, your dataset represents real measurements over time. There's a clear trend in the data, but it's muddied by the noise in each data point. One way to focus on the trend is to perform a moving average. Each data point is the average of the n
points around it (the window).
Your task is to write a function that takes a sequence of numbers and returns a sequence of weighted averages. Make n
(the window size) an argument.
(moving-average 1 [10 11])
Error printing return value (IndexOutOfBoundsException) at clojure.lang.RT/subvec (RT.java:1616)
The args are swapped in the map-indexed call. You want the index (not %2) so you need to use the (fn [i _] ...) notation.
Also, window probably should never return an empty vector as that will blow up in avg with a divide by zero.
(window 1 [10 11 12] 0)
;=> []
You could change the end calculation to be (min (count values) (+ i (max 1 n2))) but maybe there's a better way.