Skip to content

Instantly share code, notes, and snippets.

@tamaki-shingo
Last active October 5, 2016 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamaki-shingo/d41e9c6c54b7ed248641fe59a0bc3001 to your computer and use it in GitHub Desktop.
Save tamaki-shingo/d41e9c6c54b7ed248641fe59a0bc3001 to your computer and use it in GitHub Desktop.
extension Array where Element: FloatingPoint {
func simpleMovingAverage(scope:Int) -> [Element]? {
guard self.count >= scope else { return nil }
var result = [Element]()
for endIndex in scope...self.count {
let lower = endIndex-scope
let upper = endIndex
let range = Range(uncheckedBounds: (lower: lower, upper: upper))
let sum = self[range].reduce(0) { (v1, v2) -> Element in return v1+v2 }
let avg = sum/Element(scope)
result.append(avg)
}
return result
}
}
/// try this with swift playground
//let case1 = ((Array<Int>)(0...180)).map{Double($0) + Double(arc4random_uniform(300))/10}.simpleMovingAverage(scope: 10)
//let case2 = ((Array<Int>)(0...9)).map{Double($0) + Double(arc4random_uniform(300))/10}.simpleMovingAverage(scope: 10)
//let case3 = ((Array<Int>)(0...8)).map{Double($0) + Double(arc4random_uniform(300))/10}.simpleMovingAverage(scope: 10)
//case1
//case2
//case3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment