16
2
Note: This is #3 in a series of array-manipulation challenges. For the previous challenge, click here.
Moving Average of a List
The moving average of a list is a calculation resulting in a new, smoothed out list, created by averaging small overlapping sublists of the original.
When creating a moving average, we first generate the list of overlapping sublists using a certain 'window size', shifting this window to the right once each time.
For example, given the list [8, 4, 6, 2, 2, 4]
and the window size 3
, the sublists would be:
[8, 4, 6, 2, 2, 4] Sublists:
( ) <- [8, 4, 6]
( ) <- [4, 6, 2]
( ) <- [6, 2, 2]
( ) <- [2, 2, 4]
We then calculate the mean average of each sublist to obtain the result: [6.0, 4.0, 3.3, 2.7]
(each value rounded to one decimal place).
The Challenge
Your task is to write a program or function which, given a list L, and an integer 1 ≤ n ≤ length(L), calculate the moving average for L using the window size n.
Rules:
- Your program may use integer division or float division. In the case of float division, small inaccuracies due to the data type's limitations are permitted, as long as the value is otherwise correct.
- You may submit a full program, or a function (but not a snippet).
- You may assume that the list will only contain positive integers.
- Standard loopholes are forbidden.
- This is code-golf, so the shortest answer (in bytes) wins!
Test Cases
Note that, for ease of readability, all values are rounded to one decimal place.
n=5, [1, 2, 3, 4, 5, 6, 7, 8] -> [3, 4, 5, 6]
n=3, [100, 502, 350, 223, 195] -> [317.3, 358.3, 256]
n=1, [10, 10, 10] -> [10, 10, 10]
n=3, [10, 20, 30] -> [20]
n=2, [90, 40, 45, 100, 101] -> [65, 42.5, 72.5, 100.5]
Do we have to round float values, or can we leave them as they are? – caird coinheringaahing – 2017-11-05T16:01:05.887
3@cairdcoinheringaahing *Note that, for ease of readability, all values are rounded to one decimal place*. In my opinion, you can definitely leave them as they are (at least that's what I understand). – Mr. Xcoder – 2017-11-05T16:01:29.623
@cairdcoinheringaahing I've been quite liberal with I/O: integer or float values are fine, you may round if you want but don't have to, and floating point errors are allowed – FlipTack – 2017-11-05T16:03:36.360
Is it okay to return fractions instead of floating point numbers? – JungHwan Min – 2017-11-05T16:23:05.440
@JungHwanMin If for accuracy, your language will store values as fractions rather than floats, it's fine to print them as accurate fractions in their simplest forms. – FlipTack – 2017-11-05T16:26:41.353
Related (sliding window on a string) – FlipTack – 2017-12-27T18:17:34.400