Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.