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.swift446 chars18 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.swift79 chars3 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.
gistlibby LogSnag