【问题标题】:How to select multiple random elements from a LUA table?如何从 LUA 表中选择多个随机元素?
【发布时间】:2021-09-20 15:20:33
【问题描述】:

我正在尝试弄清楚如何随机选择表格中的多个条目。

这是我目前拥有的


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这个帖子中发现的东西

【问题讨论】:

  • 它如何决定返回多少个字母?应该有一个函数参数吗?该功能是否允许选择重复项?

标签: lua lua-table


【解决方案1】:

你可以...

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

【讨论】:

    【解决方案2】:
    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 会返回一个空字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-12
      • 2014-02-07
      • 1970-01-01
      • 2014-11-21
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多