HyperProduct
HyperProduct

Reputation: 15

Randomly choosing from an array without repetitions

I'm having trouble trying to figure out how I would go about choosing a phrase from an array randomly, without having multiple phrases appear twice in a row. For example, if I had this list of phrases:

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

I would pick from them randomly using this:

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

But if I ran that line multiple times, how would I make different phrases appear every time, until it runs out of phrases, while it still being randomized? Is there an easy way to do that?

Upvotes: 1

Views: 438

Answers (2)

trincot
trincot

Reputation: 350252

Why not start with a copy of the original list, and then each time you randomly pick an element, remove it from that list. The count will automatically decrease, so your next pick will again be evenly spread over the remaining items. Then when the list runs out, start again with a fresh copy of the original list.

Here is a possible script:

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())

Upvotes: 1

I do not know Lua but I think the following should be possible in Lua.

How about introducing a new array whose elements represent indexes of phraseList: idx = {0, 1, 2, 3, 4, 5}. Then randomly arrange the elements of idx. Finally, use the elements of idx in sequence to choose the elements of phraseList? - john

Upvotes: 0

Related Questions