Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An answer to an interview question: "Say you have a list of a random type (but its the same type throughout), in an arbitrary order. how do you find the most common item in the list?"
def find_common(collection)
sorted = {}
most = [0,0]
for item in collection do
if not sorted.key? item then
sorted[item] = 0
end
sorted[item] += 1
if most[1] < sorted[item] then
most[0] = item
most[1] = sorted[item]
end
end
return most
end
item, count = find_common([1, 2, 1, 3, 1, 4, 1, 5])
puts "item: #{item} => count: #{count}"
# [nchambers@shell ~]$ ruby find_common.rb
# item: 1 => count: 4
# [nchambers@shell ~]$
func find_common(items: [Int]) -> [Int] {
var sorted = [Int: Int]()
var most = [0, 0]
for item in items {
if sorted[item] == nil {
sorted[item] = 0
}
sorted[item]! += 1
if most[1] < sorted[item]! {
most[0] = item
most[1] = sorted[item]!
}
}
return most
}
var item_count = find_common(items: [1, 2, 1, 3, 1, 4, 1, 5])
print("item: \(item_count[0]) => count: \(item_count[1])")
// Nicholass-MBP:swift nchambers$ swift find_common.swift
// item: 1 => count: 4
// Nicholass-MBP:swift nchambers$
erica commented Jan 22, 2017 edited
import Foundation

extension Array where Element: Hashable {
    /// Returns most popular member of the array
    ///
    /// - SeeAlso: https://en.wikipedia.org/wiki/Mode_(statistics)
    ///
    func mode() -> (item: Element?, count: Int) {
        let countedSet = NSCountedSet(array: self)
        let counts = countedSet.objectEnumerator()
            .map({ (item: $0 as? Element, count: countedSet.count(for: $0)) })
        return counts.reduce((item: nil, count: 0), {
            return ($0.count > $1.count) ? $0 : $1
        })
    }
    
}

let result = [1, 2, 1, 3, 1, 4, 1, 5].mode()
print("Item:", result.item ?? "No item", "Count:", result.count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment