Last active
December 5, 2023 10:26
-
-
Save denpazakura/2a8e53c2960aed849e20fc912cb9d046 to your computer and use it in GitHub Desktop.
Calculating modes in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculating modes in Swift | |
func modes<T: BinaryFloatingPoint & Hashable>(sample: Array<T>) -> Array<T> { | |
let mapped = sample.map { ($0, 1) } | |
let counts = Dictionary(mapped, uniquingKeysWith: +) | |
let max_count = counts.values.max() ?? 0 | |
let modes = counts.filter { $0.value == max_count }.map { $0.key } | |
return modes | |
} | |
print(modes(sample: sample2.map( {Double($0)} ))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment