Last active
May 2, 2020 20:29
-
-
Save gabrielepalma/cc77ac7ebf0dd1698065d941c80096bf to your computer and use it in GitHub Desktop.
Mode
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
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