Anonymous user
Averages/Mode: Difference between revisions
Add basic Swift implementation
No edit summary |
(Add basic Swift implementation) |
||
Line 2,915:
puts [mode 1 1 2 4 4]; # --> 1 4</lang>
Note that this works for any kind of value.
=={{header|Swift}}==
{{works with|Swift|4}}
This solution uses an extension of the Collection type to add a mode method. The only additional requirement of the Collection is that its Element conforms to Hashable.
<lang Swift>
// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method.
extension Collection where Element: Hashable {
/// Return a Mode of the function, or nil if none exist.
func mode() -> Element? {
var frequencies = [Element: Int]()
// Standard for loop. Can also use the forEach(_:) or reduce(into:) methods on self.
for element in self {
frequencies[element] = (frequencies[element] ?? 0) + 1
}
// The max(by:) method used here to find one of the elements with the highest associated count.
if let ( mode, _ ) = frequencies.max(by: { $0.value < $1.value }) {
return mode
} else {
return nil
}
}
}
["q", "a", "a", "a", "a", "b", "b", "z", "c", "c", "c"].mode() // returns "a"
[1, 1, 2, 3, 3, 3, 3, 4, 4, 4].mode() // returns 3
let emptyArray: [Int] = []
emptyArray.mode() // returns nil
</lang>
=={{header|UNIX Shell}}==
|