如何从LUA表中选择多个随机元素?

问题描述

我想弄清楚如何随机选择表中的多个条目。

这是我目前拥有的


local letters = {"w","x","y","z"}


function randomletterselect()
    local randomletters = {}
    
    for i,v in pairs(letters) do
        table.insert(randomletters,i)
    end
    local letter = letters[randomletters[math.random(#randomletters)]]
    -- set multiple selected letters to the new table?

end
randomletterselect()

这里的代码用于从表中选择一个随机元素(字母)。本质上,当我运行它时,我希望它是多个随机选择的字母。例如,一次它可能选择 x,y,另一次它可能选择 x,y,z。

老实说,我发现的最接近的东西正是我想出来的,在这文章Randomly select a key from a table in Lua

解决方法

你可以...

randomletterselect=function()
local chars={}
for i=65,math.random(65,90) do
  table.insert(chars,string.char(math.random(65,90)):lower())
end
print(table.concat(chars,','))
return chars
end

randomletterselect()

...对于小写字母。

这个版本返回一个没有双精度的表...

randomletterselect=function()
local chars=setmetatable({},{__name='randomletters'})
for i=65,90 do
  table.insert(chars,string.char(i):lower())
end
for i=1,math.random(#chars) do
 table.remove(chars,math.random(#chars))
end
print(#chars,table.concat(chars,'))
return chars
end
,
local tbl = {'a','b','c','d'} -- your characters here

local MIN_NUM,MAX_NUM = 1,2 ^ #tbl - 1
-- if the length of the table has changed,MAX_NUM gonna change too

math.randomseed(os.time())

local randomNum = math.random(MIN_NUM,MAX_NUM)

local function getRandomElements(num)
    local rsl = {}
    local cnt = 1
    
    while num > 0 do
        local sign = num % 2 -- to binary
        -- if the num is 0b1010,sign will be 0101

        num = (num - sign)/2
        
        if sign == 1 then
            local idx = #rsl + 1
            -- use tbl[#tbl + 1] to expand the table (array)
            
            rsl[idx] = tbl[cnt]
        end
        
        cnt = cnt + 1
    end
    
    return table.concat(rsl)
end

print(getRandomElements(randomNum))

我有另一种方法可以解决问题,请尝试。 MIN_NUM 应该是 1 因为当它为 0 时,getRandomElements 将返回一个空字符串