What is the best way to randomize components inside of a table? How would you approach this task.
Here is an example of what I am trying to do:
local table1 = {}
local players = game.Players:GetPlayers()
for i,v in pairs(players) do
wait()
NMBofplayers += 1
table.insert(table1, math.random(1, v.Name)) -- trying to randomize the table.insert, how do I approach this?
end
The table.inset above does not work its just an example of what I’m trying to do.
I’m looking for either a way to randomize the order of the names already inside the table or select a random name to insert into the table within the table.insert().
I would approach this task with looking at what has already been made.
@sleitnick has made a great module for it within AGF with table shuffle which uses an algorithm for it:
--[[
Shuffle:
Shuffles (i.e. randomizes) an array. This uses the Fisher-Yates algorithm.
local tbl = {1, 2, 3, 4, 5, 6, 7, 8, 9}
TableUtil.Shuffle(tbl)
print(table.concat(tbl, ", ")) -- e.g. > 3, 6, 9, 2, 8, 4, 1, 7, 5
--]]
local function Shuffle(tbl)
assert(type(tbl) == "table", "First argument must be a table")
local rng = Random.new()
for i = #tbl, 2, -1 do
local j = rng:NextInteger(1, i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
end
I tried using the table.sort meathod you’ve given me but I get this error:
ServerScriptService.Scripts.Script:6: invalid order function for sorting
Here is the test code:
local table1 = {"me1", "me2", "m33", "me4", "me5"}
while true do
wait(5)
table.sort(table1, function() -- new
return Random.new():NextNumber() -- new
end)
print(table.concat(table1, "PlayerName: "))
for i,v in pairs(table1) do
table.remove(table1, v)
end
end
table.sort relies on a pure comparison between values thru the algorithm, so returning a random number will not give you the expected results. You should use the Fisher-yates shuffle function instead. It’s a simple algorithm and usually the exact algorithm you will find in any array shuffle function.
local function Shuffle(tbl)
assert(type(tbl) == "table", "First argument must be a table")
local rng = Random.new()
for i = #tbl, 2, -1 do
local j = rng:NextInteger(1, i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
end
local players = game.Players:GetPlayers()
Shuffle(players)