Skip to content

Instantly share code, notes, and snippets.

@adamloving
Created March 10, 2015 18:48
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 adamloving/1a3226eed53eeb9baa39 to your computer and use it in GitHub Desktop.
Save adamloving/1a3226eed53eeb9baa39 to your computer and use it in GitHub Desktop.
Swift: Sort array of strings by the frequency (how many times) they appear in an array.
// Sort in order by frequency (descending)
var terms = ["a", "b", "a", "c", "a", "b"]
var termFrequencies = [String: Int]()
for t in terms {
if termFrequencies[t] == nil {
termFrequencies[t] = 1
} else {
termFrequencies[t] = termFrequencies[t]! + 1
}
}
println(termFrequencies)
var sortedTerms = termFrequencies.keys.array
sortedTerms.sort({ termFrequencies[$0] > termFrequencies[$1] })
println(sortedTerms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment