从一个数组中随机选择,且不重复。

我正在困惑如何从一个数组中随机选择一个短语,而不会让多个短语连续出现两次。例如,如果我有这样的短语列表:

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

我将使用以下方法随机选择它们:

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

但如果我运行该行多次,如何使每次都出现不同的短语,直到用完所有短语,同时仍然是随机的?有简单的方法吗?

点赞
用户5459839
用户5459839

为什么不先复制一份原始列表,每次随机选择一个元素时,从列表中将其删除。计数将自动减少,因此您下一个选择将再次平均地分布在剩余项目上。然后,当列表用完时,再从原始列表开始。

下面是一个可能的脚本:

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

function pickPhrase()
    local i
    -- 如果短语用完了,就复制原始表
    if #copyPhraseList == 0 then
        for k,v in pairs(phraseList) do
            copyPhraseList[k] = v
        end
    end

    -- 从复制品中随机选择一个元素
    i = math.random(#copyPhraseList)
    phrase = copyPhraseList[i]

    -- 从复本中删除该短语
    table.remove(copyPhraseList, i)

    return phrase
end

-- 根据需要调用多次:
print (pickPhrase())
print (pickPhrase())
2015-11-01 23:16:59
用户4092830
用户4092830

我不懂 Lua,但是我认为在 Lua 中应该可以实现以下操作。

创建一个新的数组,其元素表示 phraseList 的索引:idx = {0, 1, 2, 3, 4, 5}。然后随机排列 idx 的元素。最后,按照 idx 的顺序使用它的元素选择 phraseList 的元素。- john

2015-11-01 23:43:53