Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count frequency of elements into an array in Lua

Tags:

lua

lua-table

I have a table in Lua:

p = {'sachin', 'sachin', 'dravid', 'Dhoni', 'yuvraj', 'kohli'}

I want to count frequency of each name in table .

test1 = {sachin=2, dravid=1, Dhoni=1, yuvraj=1, kohli=1}

I tried this program with lot of for loops .Please see my code

> function exec(ele,p)
count = 0
for k,v in pairs(p) do
if ele == p[k] then
count = count +1 
end
end
return count
end


> new_table = {}
> for k,v in pairs(p) do
new_table[v] = exec(v,p)
end
> 
> for k,v in pairs(new_table) do
print(k,v)
end
dhone   1
yuvraj  1
kohli   1
sachin  2
dravid  1

I want to do this more efficient way. How can I achieve this?

like image 538
Prashant Gaur Avatar asked Jul 02 '26 07:07

Prashant Gaur


2 Answers

You can count the frequency like this:

function tally(t)
  local freq = {}
  for _, v in ipairs(t) do
    freq[v] = (freq[v] or 0) + 1
  end
  return freq
end

And here's another demo example.

like image 130
greatwolf Avatar answered Jul 05 '26 17:07

greatwolf


Using metatable may be a little unnecessary for this simple case, just showing another option:

local mt = {__index = function() return 0 end}
local newtable = {}
setmetatable(newtable, mt)

for _, v in pairs(p) do
    newtable[v] = newtable[v] + 1
end

The metamethod __index above gives the table 0 as the default value.

like image 39
Yu Hao Avatar answered Jul 05 '26 15:07

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!