Search code examples
lua

beginner lua: check array for value


I need to generate a random number and then check to see which tables (arrays) that number is listed in as a value. After the check is complete I need to output the tables in which the numbers appear.

For example a random number between 1 and 21 would be generated and then be searched for within other tables of numbers.

evens = {2,4,6,8,10,12,14,16,18,20}
odds = {1,3,5,7,9,11,13,15,17,19,21}
low = {1,2,3,4,5,6,7}
med = {8,9,10,11,12,13,14}
high = {15,16,17,18,19,20,21}

If 17 was the random number, I would need 'odds' and 'high' to be output.


Solution

  • The most general solution I can offer is to build something like inverted index. You just need to create a record in a table for each possible term(a number, in your case). Values in such table represents arrays in which you can find your term. The code can look like this:

    local evens = { 2, 4, 6, 8, name = 'evens'}
    local odds = {1, 3, 5, 7, name = 'odds'}
    local low = { 1, 2, 3, 4, name = 'low'}
    local high = {15, 16, 17, 18, 19, name = 'high'}
    
    local inv_index = {}
    
    function add_to_index(index, numbers)
        for i, number in ipairs(numbers) do
                local indexed = index[number]
                if not indexed then
                        index[number] = { numbers }
                else
                        table.insert(indexed, numbers)
                end
        end
    end
    
    add_to_index(inv_index, evens)
    add_to_index(inv_index, odds)
    add_to_index(inv_index, low)
    add_to_index(inv_index, high)
    
    -- which arrays contains the number "4"?
    for k, indexed in pairs(inv_index[4]) do
        print(indexed.name) -- prints "evens" and "low"
    end
    

    The downside of this solution is the memory consumption, especially if the number of possible numbers is big. The alternative is to sort each array and perform a binary search on it. There is an implementation for lua.

    If you can modify your arrays, you can just store numbers in a some kind of set:

    local evens = { [2] = true, [4] = true, [6] = true, [8] = true }
    local low = { [1] = true, [2] = true, [3] = true, [4] = true }
    local odds = { [1] = true, [3] = true , [5] = true, [7] = true }
    
    local x = 4
    
    print(evens[x] ~= nil) -- true
    print(low[x] ~= nil) -- true
    print(odds[x] ~= nil) -- false