find the mode of all elements in an array in swift

To find the mode or most frequently occurring element of an array, we can follow the below steps:

  1. Create an empty dictionary.
  2. Loop through the array and count the frequency of each element by adding it to the dictionary.
  3. Find the element with the maximum frequency in the dictionary.

Here's an implementation in Swift:

main.swift
func findMode<T: Hashable>(in array: [T]) -> T? {
    var frequency: [T: Int] = [:]
    array.forEach { frequency[$0, default: 0] += 1 }
    
    if let max = frequency.values.max(), let mode = frequency.first(where: { $0.value == max })?.key {
        return mode
    }
    return nil
}
288 chars
10 lines

The function takes an array of generic type T, which must be hashable so that we can store it in the dictionary. We create an empty dictionary to store the frequency of each element of the array. Then we loop through the array and add each element to the dictionary, incrementing its count if it already exists in the dictionary.

Finally, we find the maximum frequency by getting the maximum value from the dictionary's values, and then find the mode by searching for the first key in the dictionary that has the maximum frequency. If there are multiple modes with the same frequency, this implementation will return the first one found.

Example usage:

main.swift
let array = [1, 2, 2, 3, 4, 4, 4, 5]
if let mode = findMode(in: array) {
    print("The mode of the array is: \(mode)") // prints "The mode of the array is: 4"
} else {
    print("The array is empty.")
}
204 chars
7 lines

gistlibby LogSnag