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.

Calculations

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.

Unit Tests

And, of course, where would I be without unit tests?

Addendum: Efficiency

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.

The Problem
Developing an Android app, using Android’s Navigation Components, and after returning to the first fragment, the button to go to the second frag...

I recently purchased a TicWatch E2. It’s my first smartwatch, so I thought I’d collect my thoughts on it, Wear OS, and smart watches in general. This is my...

Moving Average Package
Moving Average is a Dart library to calculate moving averages of numbers.
Currently it works only on List<num>, but I’m consid...

Six months ago I blogged my initial impressions about the TicWatch E2. Here is my review after six months of use.
Initial Expectations
How has it lived up...

## Comments