-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathArray+Median.swift
33 lines (30 loc) · 953 Bytes
/
Array+Median.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//
// Array+Median.swift
//
// Advent of Code Tools
//
// we need two implementations because there is no common protocol for numerics that supports division
extension Array where Element: BinaryInteger {
// return the middle element (if count is odd) or the average the "two middle" elements
public func median() -> Element {
if count.isMultiple(of: 2) {
let v1 = self[count / 2]
let v2 = self[count / 2 - 1]
return (v1 + v2) / 2
} else {
return self[count / 2]
}
}
}
extension Array where Element: FloatingPoint {
// return the middle element (if count is odd) or the average the "two middle" elements
public func median() -> Element {
if count.isMultiple(of: 2) {
let v1 = self[count / 2]
let v2 = self[count / 2 - 1]
return (v1 + v2) / 2
} else {
return self[count / 2]
}
}
}