Skip to content

Instantly share code, notes, and snippets.

@hirohitokato
Last active May 16, 2016 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hirohitokato/5bfc5836480d68074135820d73c04794 to your computer and use it in GitHub Desktop.
Save hirohitokato/5bfc5836480d68074135820d73c04794 to your computer and use it in GitHub Desktop.
A moving average of the specified array by Swift. It is merged from https://gist.github.com/norio-nomura/fdbf22dacefcfcf87705cf2cd8fb846f
// merged from https://gist.github.com/norio-nomura/fdbf22dacefcfcf87705cf2cd8fb846f
import Foundation
public protocol ArithmeticType: IntegerLiteralConvertible {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
extension Int: ArithmeticType {}
extension CGFloat: ArithmeticType {}
extension Double: ArithmeticType {}
extension Float: ArithmeticType {}
// Calculate moving average of the specified array.
// @see: https://ja.wikipedia.org/wiki/%E7%A7%BB%E5%8B%95%E5%B9%B3%E5%9D%87
#if swift(>=3)
// tested on swift-DEVELOPMENT-SNAPSHOT-2016-05-09-a
public extension Collection where Iterator.Element: ArithmeticType {
@_specialize(Array<Int>)
@_specialize(Array<CGFloat>)
@_specialize(Array<Double>)
@_specialize(Array<Float>)
public func movingAverage() -> Iterator.Element {
var i: Iterator.Element = 0
let numer = reduce(i) {
i = i + 1
return $0 + $1 * i
}
let denom = i * (i + 1) / 2
return numer / denom
}
}
#else
public extension CollectionType where Generator.Element: ArithmeticType {
public func movingAverage() -> Generator.Element {
var i: Generator.Element = 0
let numer = reduce(i) {
i = i + 1
return $0 + $1 * i
}
let denom = i * (i + 1) / 2
return numer / denom
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment