Lafolie wrote:I find that at least 3 randoms are needed before it starts spitting out anything different.
Remember that a sequence of numbers where no two neighboring numbers are the same is exactly the opposite of random. Repetitions will occur more frequently the fewer numbers you choose from. You can try it yourself by throwing a die multiple times.
For the lazy, this is such a sequence: 5, 5, 5, 3, 5, 1, 2, 4, 5, 3, 5, 4, 3, 1, 3, 1, 1, 2, 6, 4, 3, 6, 3, 1, 6, 6, 4.
I'm sure you can find some "patterns" in there. If you reduce this to three numbers by mapping 1&2 to 1, 3&4 to 2 and 5&6 to 3, you get the sequence: 3, 3, 3, 2, 3, 1, 1, 2, 3, 2, 3, 2, 2, 1, 2, 1, 1, 1, 3, 2, 2, 3, 2, 1, 3, 3, 2.
What you probably want is NOT truly random (read:
statistical independent) behavior, but a "random bag", where each element is chosen randomly and then removed from the bag. Once the bag is empty, it is filled again:
Code: Select all
function random_bag(values)
local bag = {}
local function refill()
for i,v in ipairs(values) do bag[i] = v end
-- shuffle the bag
for i=#bag,2,-1 do
local k = math.random(1,i)
bag[i], bag[k] = bag[k], bag[i]
end
end
return function()
if #bag == 0 then refill() end
return table.remove(bag)
end
end
Use it like so:
Code: Select all
bag = random_bag({"music1.mp3", "music2.mp3", "music3.mp3"})
print(bag()) --> music1.mp3
print(bag()) --> music3.mp3
print(bag()) --> music2.mp3
print(bag()) --> music1.mp3