I want to get the most frequent k-sized substring in a string. To achieve this, I'm using a table to store the number of occurrences for each substring. Here's the code:
function frequentWords(seq, k)
local subs = ""
local counter = {}
for i = 1,(seq:len()-k+1) do
subs = seq:sub(i, i+k-1)
counter[subs] = (counter[subs] and counter[subs] + 1 or 1)
--print(subs .. ": " .. counter[subs])
end
end
The line counter[subs] = (counter[subs] and counter[subs] + 1 or 1)
has the same mean of counter[subs] = (counter[subs] ? counter[subs]+1 : 1)
. This line would be only counter[subs] = counter[subs] + 1
if we could set every new counter
element with 0
. Is this possible in Lua? If not, what's the best way of doing something similar?
For instance, in Ruby, this is done by declaring a Hash like this:
counter = Hash.new(0)
You can set an __index
metamethod in counter
to return 0:
setmetatable(counter,{__index=function () return 0 end})
but this is easier and clearer:
counter[subs] = (counter[subs] or 0) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With