Last active
October 5, 2016 20:12
-
-
Save tamaki-shingo/d41e9c6c54b7ed248641fe59a0bc3001 to your computer and use it in GitHub Desktop.
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 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