Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norio-nomura/fdbf22dacefcfcf87705cf2cd8fb846f to your computer and use it in GitHub Desktop.
Save norio-nomura/fdbf22dacefcfcf87705cf2cd8fb846f to your computer and use it in GitHub Desktop.
A moving average of the specified collection by Swift 3. Forked from https://gist.github.com/hirohitokato/5bfc5836480d68074135820d73c04794
//
// Collection+movingAverage.swift
//
// inspired by https://gist.github.com/hirohitokato/5bfc5836480d68074135820d73c04794
import Foundation
public protocol ArithmeticType: Comparable, 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
Copy link

ghost commented Jul 8, 2017

Could you give some instruction on this

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