Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gabrielepalma/cc77ac7ebf0dd1698065d941c80096bf to your computer and use it in GitHub Desktop.
Save gabrielepalma/cc77ac7ebf0dd1698065d941c80096bf to your computer and use it in GitHub Desktop.
Mode
import Foundation
extension Sequence where Element: Hashable {
public func mode() -> [Element] {
var freq = [Element:Int]()
self.forEach { freq[$0] = (freq[$0] ?? 0)+1 }
var max = freq.values.max()
return freq.filter { $0.1 == max }.map { $0.0 }
}
}
print("Protocol Oriented Programming is amazing!".mode())
print([1,1,1,1,2,3,10].mode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment