从数组中随机选择而不重复

时间:2015-11-01 23:11:50

标签: arrays random lua

我无法弄清楚如何随机地从数组中选择一个短语,而不会连续两次出现多个短语。例如,如果我有这个短语列表:

phraseList = {"pig","cow","cat","dog","horse","mouse","giraffe"}

我会随机选择它们:

startPhrase = phraseList[math.random(#phraseList)]

但是如果我多次运行该行,那么每次都会出现不同的短语,直到它用完短语,而它仍然是随机的?有没有一种简单的方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

为什么不从原始列表的副本开始,然后每次随机选择一个元素,将其从该列表中删除。计数将自动减少,因此您的下一个选择将再次均匀分布在剩余的项目上。然后当列表用完时,再次使用原始列表的新副本重新开始。

这是一个可能的脚本:

local phraseList = {"pig","cow","cat","dog","horse","mouse","giraffe"}
local copyPhraseList = {}

function pickPhrase()
    local i
    -- make a copy of the original table if we ran out of phrases
    if #copyPhraseList == 0 then
        for k,v in pairs(phraseList) do
            copyPhraseList[k] = v
        end
    end

    -- pick a random element from the copy  
    i = math.random(#copyPhraseList)
    phrase = copyPhraseList[i] 

    -- remove phrase from copy
    table.remove(copyPhraseList, i)

    return phrase
end

-- call it as many times as you need it:
print (pickPhrase())
print (pickPhrase())

答案 1 :(得分:0)

我不认识Lua,但我认为在Lua中应该可以使用以下内容。

如何引入一个新数组,其元素表示phraseList的索引:idx = {0,1,2,3,4,5}。然后随机排列idx的元素。最后,依次使用idx的元素来选择phraseList的元素? - 约翰