I’m working on an app that calculates and displays moving averages for a list of numbers. This post shows how I’m doing it in Kotlin, using list operations instead of iteratively. The source code for this is available on GitHub.
First I pull out all the sub-lists of the required size. For my purposes, I also want the short sublists at the start, of size 1, 2, …, n.
Next comes a couple of functions to calculate means, both standard, and weighted. These are extension functions in Iterable.
With these I can now calculate the moving averages. The following code pulls it all together.
And, of course, where would I be without tests?
The above calculation is not memory efficient. For a list of 1,000 numbers, and a window size of 10, it would create 1,000 lists of 10 numbers, and then calculate the avarages of each list. That’s not too bad for small lists, but could get out of hand for large lists and window sizes.
What can I do about that?
Kotlin Sequences provide a way to lazily evaluate collections. New in Kotlin 1.2 is Sequence<T>.windowed(…) which will lazily provide a sequence of sliding windows that I can then use in my calculations.