Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created January 10, 2016 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/a11d82a7801c90207140 to your computer and use it in GitHub Desktop.
Save rayfix/a11d82a7801c90207140 to your computer and use it in GitHub Desktop.
Generic frequencies method for SequenceTypes
//: # 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