Skip to content

Instantly share code, notes, and snippets.

@denpazakura
Last active December 5, 2023 10:26
Show Gist options
  • Save denpazakura/2a8e53c2960aed849e20fc912cb9d046 to your computer and use it in GitHub Desktop.
Save denpazakura/2a8e53c2960aed849e20fc912cb9d046 to your computer and use it in GitHub Desktop.
Calculating modes in Swift
# 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