Last active
January 24, 2017 19:52
-
-
Save briancordanyoung/376063c65443b4a75853f6405a832e47 to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
extension Array where Element: Hashable { | |
/// Returns most popular member of the array | |
/// | |
/// - SeeAlso: https://en.wikipedia.org/wiki/Mode_(statistics) | |
/// | |
typealias ArrayMode = (item: Element?, count: Int) | |
func mode() -> (item: Element?, count: Int) { | |
let countedSet = NSCountedSet(array: self) | |
let counts: [ArrayMode] = countedSet.objectEnumerator() | |
.map { | |
let item = $0 as? Element | |
return ArrayMode(item: item, | |
count: countedSet.count(for: $0)) | |
} | |
let emptyResult = ArrayMode(item: nil, | |
count: 0) | |
return counts.reduce(emptyResult) { | |
return ($0.count > $1.count) ? $0 : $1 | |
} | |
} | |
} | |
[5,5,1,4,2,5,3,3,4,1,5].mode() // ({some 5}, .1 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment