Skip to content

Instantly share code, notes, and snippets.

@BasThomas
Last active April 4, 2023 10:16
Show Gist options
  • Save BasThomas/d049f845d688dac5c06ca68af1f3ca1b to your computer and use it in GitHub Desktop.
Save BasThomas/d049f845d688dac5c06ca68af1f3ca1b to your computer and use it in GitHub Desktop.
Calculate a moving average in Swift (Swift 4.1)
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)
}
}
@sultan-arshi
Copy link

it should have another parameter for moving index/window some thing describe in the moving Mean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment