word_freq.lua in Lua
A word-frequency table from gmatch, a tally table, and one sort.
-- Count word frequencies in a passage and chart the leaders.
local passage = "the rain in maine falls mainly on the plain and "
.. "the rain stays on the plain"
-- Tally every word with gmatch; missing keys start at zero.
local counts = {}
for word in passage:gmatch("%a+") do
counts[word] = (counts[word] or 0) + 1
end
-- Move to an array and sort: count descending, ties by word.
local ranked = {}
for word, n in pairs(counts) do
ranked[#ranked + 1] = { word = word, n = n }
end
table.sort(ranked, function(a, b)
if a.n ~= b.n then return a.n > b.n end
return a.word < b.word
end)
print(#ranked .. " distinct words")
print("word ct bar")
for _, entry in ipairs(ranked) do
print(string.format("%-7s %2d %s",
entry.word, entry.n, string.rep("#", entry.n)))
end
How it works
gmatch("%a+")iterates the words;or 0seeds the tally.- Pairs move into an array so
table.sortcan rank them. string.rep("#", n)draws each word's bar.
Keywords and builtins used here
doendforfunctiongmatchifinipairslocalpairsprintreturnthen
The run, in numbers
- Lines
- 27
- Characters to type
- 768
- Tokens
- 167
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 154 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.