find the mode of all keys in a map in swift

To find the mode of all keys in a Swift dictionary, we can use the following algorithm:

  • Create a dictionary where the keys are the keys in the input dictionary and the values are the number of occurrences each key appears in the input dictionary.
  • Sort the dictionary by the value in descending order.
  • Return the first key in the sorted dictionary.

Here's the Swift code to implement this algorithm:

main.swift
extension Dictionary where Key: Hashable {
    func mode() -> Key? {
        let counts = reduce(into: [:]) { counts, pair in counts[pair.key, default: 0] += 1 }
        let sortedCounts = counts.sorted { $0.value > $1.value }
        return sortedCounts.first?.key
    }
}

// Example usage
let dict = ["apple": 3, "banana": 1, "orange": 3, "pear": 2]
let mode = dict.mode() // "apple"
387 chars
12 lines

In the above code, we create an extension on the Dictionary type and add a mode() method which returns the mode key of the dictionary. We leverage the reduce(into:) method to count the number of occurrences of each key in the input dictionary. Then we sort the counts in descending order and return the first key.

Note that if there are ties for the most frequent key, this code will only return one of the tied keys. Additionally, if the input dictionary is empty, this code will return nil.

gistlibby LogSnag