Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning key of maximum or minimum number in a table

Tags:

lua

lua-table

A simple Lua problem here: how to find the index, or key, of the minimum or maximum number in a given table.

math.max/math.min only gives the actual max or min number, not the key.

like image 484
Lucien S. Avatar asked Dec 29 '13 16:12

Lucien S.


2 Answers

Iterate the table, and compare the value with the stored max/min value. Take getting the max as an example(assuming the table is a sequence, i.e, array-like:

local t = {1, 3, 7, 6, 4, 0}

local key, max = 1, t[1]
for k, v in ipairs(t) do
    if t[k] > max then
        key, max = k, v
    end
end

print(key, max)

Output:

3       7

If the table is not a sequence, a little improvement would do:

local t = {four = 4, three = 3, seven = 7, six = 6, one = 1, zero = 0}

local key = next(t)
local max = t[key]

for k, v in pairs(t) do
    if t[k] > max then
        key, max = k, v
    end
end

print(key, max)

In real code, remember to check if the table is empty first.

like image 117
Yu Hao Avatar answered Nov 10 '22 16:11

Yu Hao


function maxkey(initialtable)
 local maxval = math.max(unpack(initialtable))
 local inv={}
 for k,v in pairs(initialtable) do
   inv[v]=k
 end
 return inv[maxval]
end

See these SO questions:

  • Lua find a key from a value
  • How do I get the highest integer in a table in Lua?
like image 34
lincb Avatar answered Nov 10 '22 15:11

lincb