Created
January 10, 2016 02:23
-
-
Save rayfix/a11d82a7801c90207140 to your computer and use it in GitHub Desktop.
Generic frequencies method for SequenceTypes
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
//: # Generic frequencies for SequenceType | |
//: | |
//: Based on a tweet from Airspeed Velocity @airspeedswift | |
//: describing a custom subscript operation that takes | |
//: an initial value if the key is not found. | |
import Foundation | |
extension Dictionary { | |
subscript(key: Key, or initial: Value) -> Value { | |
get { | |
return self[key] ?? initial | |
} | |
set { | |
self[key] = newValue | |
} | |
} | |
} | |
extension SequenceType where Generator.Element: Hashable { | |
typealias Key = Generator.Element | |
func frequencies() -> [Key:Int] { | |
var output: [Key: Int] = [:] | |
for value in self { | |
output[value, or: 0] += 1 | |
} | |
return output | |
} | |
} | |
let message = "Now is the time for all good people to come to the aid of their country." | |
let wordCount = message.componentsSeparatedByString(" ").frequencies() | |
(1...10).frequencies() | |
[1,2,4,5,2,1,1,1].frequencies() | |
message.characters.frequencies() | |
let sorted = wordCount.sort { $0.1 > $1.1 } | |
sorted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment