find the mode of a list of numbers in swift

To find the mode of a list (or array) of numbers in Swift, we can use a dictionary to count the frequency of each element, and then find the element(s) with the highest count. Here's an example implementation:

main.swift
func mode(list: [Int]) -> [Int] {
    var counts = [Int: Int]()
    // count frequency of each element
    for element in list {
        counts[element, default: 0] += 1
    }
    // find element(s) with highest count
    var mode = [Int]()
    if let maxCount = counts.values.max() {
        for (element, count) in counts {
            if count == maxCount {
                mode.append(element)
            }
        }
    }
    return mode
}
446 chars
18 lines

We first initialize an empty dictionary counts to store the frequency of each element. Then we loop through the list, incrementing the count for each element in the dictionary. Next, we find the maximum count value in the dictionary using counts.values.max(). Finally, we loop through the dictionary again to find the element(s) with the same count as the maximum count, and append them to our mode array. We then return the mode array.

Here's an example usage:

main.swift
let myList = [1, 2, 3, 3, 4, 5, 5]
print(mode(list: myList)) // Output: [3, 5]
79 chars
3 lines

In this example, the mode(s) of the list [1, 2, 3, 3, 4, 5, 5] are [3, 5], since both 3 and 5 appear twice in the list, which is the highest count for any element in the list.

related categories

gistlibby LogSnag