Skip to content

Instantly share code, notes, and snippets.

@darhonbek
Last active October 5, 2018 14:29
Show Gist options
  • Save darhonbek/14915af45ef3f5a1f7e9e2c431db1d4d to your computer and use it in GitHub Desktop.
Save darhonbek/14915af45ef3f5a1f7e9e2c431db1d4d to your computer and use it in GitHub Desktop.
Character Frequency Counter
// MARK: - Main
var cipherText = "vyc iafgrr xl o ozpghf qw qtvitzrn zorj. rwx qascg mvtvyi bg orgcem vyc gxtnvaibcp fd dnf yvyzgsujch. mvgicuhfg, jcrnfkkw xl bqk yqhiv dyzbbi kcrabqcmvr dgidtvh, dlr btykee rngvfktk inkgbthgcw hthkjdxxr ceb rhbhzbtgh. vyc bxhjfbh mvck uxez ofqi xthvaibjgcw bbbkdgox hjv yqbzkkw dy wpkpjwstj rd vcogpdfwuv gcyctdyibcp jcrnfkkw pks efkeksjvlhbjg lqtk htrgcbbi rls xrwtyibcp. rlnpoa, tmczfcksathkfl, nhi ularxsf km sxqkgftk mqlp ubfuk ktlgcxc xg hjzq rhitjc. xy mql udky jrpsxf vycc rcw ngae pg r edhr eiwemoprjnlh. ccqd, rcw ngae pg r edhr uvajkwvp qexqkrjxlh.".lowercased()
var frequencyTable = getCharacterFrequency(of: cipherText)
let sortedTable = frequencyTable.sorted(by: {$0.0 < $1.0})
print(sortedTable)
// MARK: - Actions
func getCharacterFrequency(of text: String) -> [Character: Int] {
var frequencyTable = [Character: Int]()
for symbol in text {
if let frequency = frequencyTable[symbol] {
frequencyTable[symbol] = frequency + 1
} else {
frequencyTable[symbol] = 1
}
}
return frequencyTable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment