word_freq.swift in Swift
A word-frequency table from split, a defaulted subscript, one sort.
// Count word frequencies in a passage and chart the leaders.
import Foundation
let passage = "the rain in maine falls mainly on the plain and "
+ "the rain stays on the plain"
// Tally every word; default: reads a zero for new keys.
var counts: [String: Int] = [:]
for word in passage.split(separator: " ") {
counts[String(word), default: 0] += 1
}
// Rank the entries, biggest first, ties broken by the word itself.
let ranked = counts.sorted {
$0.value != $1.value ? $0.value > $1.value : $0.key < $1.key
}
print("\(ranked.count) distinct words")
print("word ct bar")
for (word, n) in ranked {
let padded = word.padding(toLength: 7, withPad: " ", startingAt: 0)
let count = String(n).count == 1 ? " \(n)" : "\(n)"
let bar = String(repeating: "#", count: n)
print("\(padded) \(count) \(bar)")
}
How it works
counts[word, default: 0] += 1tallies without a guard.- The sort ranks by count with alphabetical ties in one closure.
String(repeating:count:)draws each word's bar.
Keywords and builtins used here
FoundationIntStringcountdefaultforimportinletprintsortedsplitvar
The run, in numbers
- Lines
- 26
- Characters to type
- 804
- Tokens
- 188
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 174 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.