0

Suppose that I have a table:

0.8
0.7
0.9
0.5

And I want to get the index of 2 largest values, so in this case, it should return:

3 1

I am quite newbie with Lua, so any help is more than welcome.

Thanks a lot,

2
  • your question should show some own efforts to solve the problem. Commented May 19, 2016 at 17:33
  • You aren't showing the keys (indexes) from your table. If you are concerned only with positive integer keys and they will all be consecutive (no nil values before the last) then you can use table techniques that apply only to "table sequences" such as # Commented May 20, 2016 at 13:11

1 Answer 1

3

You can loop over a table using for loop (for i = 1, #tbl or for i, val in ipairs(tbl)) and keep track of the largest and second to large elements (you'll need to store first index and first value and second index with second value to check the value and save the index). After the loop is done, you get the indexes of the first and second largest elements. Keep in mind that when the first value is updated its old value may need to be checked against the second value.

Another option is to build an array of indexes and sort it based on the values (as the sort can take an optional comparator function):

local function indexsort(tbl)
  local idx = {}
  for i = 1, #tbl do idx[i] = i end -- build a table of indexes
  -- sort the indexes, but use the values as the sorting criteria
  table.sort(idx, function(a, b) return tbl[a] > tbl[b] end)
  -- return the sorted indexes
  return (table.unpack or unpack)(idx)
end
local tbl = {0.8, 0.7, 0.9, 0.5}
print(indexsort(tbl))

This prints 3 1 2 4. If you only need the first two indexes, you can do local first, second = indexsort(tbl). Note that indexsort returns all indexes, so if you only need the first two (and your table is large), you may want to update the function to only return the first two items instead of the entire table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.