To find the mode or most frequently occurring element of an array, we can follow the below steps:
Here's an implementation in Swift:
main.swift288 chars10 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.swift204 chars7 lines
gistlibby LogSnag