Lua初学者:检查数组中的值

我需要生成一个随机数,然后检查哪些表(数组)中有这个数字作为值。检查完成后,我需要输出数字出现的表。

例如,生成1到21之间的随机数,并在其他数字表中搜索。

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}

如果随机数为17,则需要输出'odds'和'high'。

点赞
用户7504558
用户7504558

为了检查是否为奇数表格并更容易检查限制范围:

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

local n = 33
local function CheckNum(n)
    local tab_type = 'unknown'
    if n >= 1 and n <= 7 then 
        tab_type = "low"
    elseif n >= 8 and n <= 14 then 
        tab_type = "med"
    elseif n >= 15 and n <= 21 then 
        tab_type = "high"
    end
    local odd = (n % 2 == 0) and "even" or "odd"
    return odd, tab_type
end

local odd, tab_type = CheckNum(n)
print(odd, " ", tab_type)
2018-11-06 08:42:53
用户10593333
用户10593333

我能提供的最常规的解决方案是构建类似于倒排索引的东西。您只需要为每个可能的术语(在您的情况下为数字)在表中创建一条记录。表中的值表示您可以找到该术语的数组。

代码可能如下所示:

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)

-- 哪些数组包含数字“4”?
for k, indexed in pairs(inv_index[4]) do
    print(indexed.name) -- 输出 “evens” 和 “low”
end

这种解决方案的缺点是内存消耗很大,尤其是如果可能的数字数量很大。另一种选择是对每个数组进行排序并进行二分搜索。在lua中有一个实现

如果您可以修改数组,则可以将数字存储在某种集合中:

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
2018-11-06 23:57:23
用户14127203
用户14127203

我找到了一个用于在列表中检查值的函数:

function contains(list,x)
    for _,v in pairs(list) do
        if v == x then return true end
    end
    return false
end

这是一个如何使用它的示例:

alist={'abc',123}
if contains(alist,'abc')
    print('abc 在列表 alist 中')
end
2021-02-24 16:51:10