Forked from hirohitokato/Collection+movingavg.swift
Last active
October 27, 2017 03:20
-
-
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
This file contains hidden or 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
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you give some instruction on this