Last active
April 4, 2023 10:16
-
-
Save BasThomas/d049f845d688dac5c06ca68af1f3ca1b to your computer and use it in GitHub Desktop.
Calculate a moving average in Swift (Swift 4.1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Collection where Element == Int, Index == Int { | |
/// Calculates a moving average. | |
/// - Parameter period: the period to calculate averages for. | |
/// - Warning: the supplied `period` must be larger than 1. | |
/// - Warning: the supplied `period` should not exceed the collection's `count`. | |
/// - Returns: a dictionary of indexes and averages. | |
func movingAverage(period: Int) -> [Int: Float] { | |
precondition(period > 1) | |
precondition(count > period) | |
let result = (0..<self.count).compactMap { index -> (Int, Float)? in | |
if (0..<period).contains(index) { return nil } | |
let range = index - period..<index | |
let sum = self[range].reduce(0, +) | |
let result = Float(sum) / Float(period) | |
return (index, result) | |
} | |
return Dictionary(uniqueKeysWithValues: result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: