Skip to content

Instantly share code, notes, and snippets.

@briancordanyoung
Last active January 24, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briancordanyoung/376063c65443b4a75853f6405a832e47 to your computer and use it in GitHub Desktop.
Save briancordanyoung/376063c65443b4a75853f6405a832e47 to your computer and use it in GitHub Desktop.
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