Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active July 30, 2018 09:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/a8ceb431651b4f8dfef97adefa8712f0 to your computer and use it in GitHub Desktop.
Save ha1f/a8ceb431651b4f8dfef97adefa8712f0 to your computer and use it in GitHub Desktop.
import Foundation
extension Array {
/// Returns unique pairs from array
/// Following is result of `[1, 2, 3, 4].pairs()`
/// [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
func pairs() -> [(Element, Element)] {
return enumerated()
.flatMap { index, element in
dropFirst(index.advanced(by: 1))
.map { (element, $0) }
}
}
}
private extension Double {
/// Calculate the average angle
/// If average does not exists, this will return Double.nan (like [0°, 180°])
static func averageAngle(_ angles: [Double]) -> Double {
let (x, y) = angles.map { (cos($0), sin($0)) }
.reduce((0, 0)) { result, item in (result.0 + item.0, result.1 + item.1) }
return atan(y / x)
}
/// Calculate the distance of periodic value
/// result x meets `0 <= x < period / 2`
static func periodicDistance(_ lhs: Double, _ rhs: Double, period: Double) -> Double {
let diff = lhs - rhs
let normalized = diff - period * floor(diff / period)
return normalized < (period / 2) ? normalized : period - normalized
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment