So I’m trying to create a map voting system but I need to select 3 new and different maps to vote on each time. I need help working out the logic to select the 3 different maps from a folder every time I call a function.
Any help is appreciated.
So I’m trying to create a map voting system but I need to select 3 new and different maps to vote on each time. I need help working out the logic to select the 3 different maps from a folder every time I call a function.
Any help is appreciated.
Create a list of the maps, shuffle it, and use the first three.
Or repeatedly pick a random index until you have three unique indices.
How would I “shuffle” the list? EDIT: Used the random index method instead, thanks!
For what it’s worth, a Fischer-Yates shuffle would work.
Edit: that answer actually looks like it changes the original table and makes a new one, which is dumb. I would just shuffle in place:
function FYShuffle( tInput )
for i = #tInput, 2, -1 do
local j = math.random(i)
tInput[i], tInput[j] = tInput[j], tInput[i]
end
end
local t = {1,2,3,4,5,6}
print(table.concat(t, ","))
-- 1,2,3,4,5,6
FYShuffle(t)
print(table.concat(t, ","))
-- 1,3,2,6,4,5
Is there a less complex way of doing it? The method I tried didn’t actually work.
Also I packed the other way (repeated random sampling until you get a new result) into an iterator:
local function random_n(t, n)
local chosen = {}
local num = 0
return function()
if num == n then return nil end
local i
repeat i = math.random(1, #t) until not chosen[i]
chosen[i] = true
num = num + 1
return i, t[i]
end
end
-- example usage
local t = {"a", "b", "c", "d", "e", "f"}
for i, v in random_n(t, 4) do
print(i, v)
end
--[[
3 c
5 e
2 b
1 a
--]]
It’s not smart for large tables, but for something like this it would be fine.
Turning the shuffle-and-choose method into an iterator is left as an exercise for the reader