Created
March 10, 2015 18:48
-
-
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.
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
// 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