【问题标题】:Randomly choosing from an array without repetitions从数组中随机选择而不重复
【发布时间】:2016-02-01 18:52:23
【问题描述】:

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

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

我会随机选择它们:

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

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

【问题讨论】:

    标签: arrays random lua


    【解决方案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())
    

    【讨论】:

    • 当短语用完时如何让列表重新启动?我想选择一个短语的次数超过列表中短语的数量。很抱歉造成混乱。
    • 但是你会有重复的吗?那不是你的限制吗?您首先要清空列表,然后才有重复项?
    • 我不想重复这些短语,除非它们必须重复。所以一旦列表用完,是的,会有重复的。我几乎不希望同一个短语连续重复两次。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多