If you’re making a round-based game that requires items or maps randomizing then I have a little tips for you.
Let’s start this by preparing the essentials. I will be making an example of randomizing maps every round.
local storage = game:GetService("ReplicatedStorage")
local mapsfolder = storage.Maps
local maps = mapsfolder:GetChildren()
For the next step, have you ever thought or did something like this?
local function LoadMap(map)
map.Parent = workspace
end
while true do
local map = maps[math.random(1,#maps)] -- <== This?
LoadMap(map)
end
Well, I’m not saying it does not work, but it’s not an efficient way to do it, and there is a reason to it.
Let’s try math.random(1,5)
and look at the output.
See how many times the number 5 and 3 keep repeatedly appearing and the number 4 only appears twice?
This is why it’s not a good way to do it.
So what other methods are there that you can use?
I will give you one method in billions of ways to do it.
Here’s my method
Let’s not use math.random to get an object from a table, but instead let’s shuffle the table!
math.randomseed(tick())
local nums = {1,2,3,4,5}
local gen = 0
while true do
Shuffle(nums) --This function will mix the nums' variables up randomly.
gen = gen + 1
print("Generation: ",gen)
for i=1,#nums do
print(nums[i])
end
wait(1)
end
Pretty neat, right? Now let’s make ourselfs a shuffle function:
local function Shuffle(tabl)
for i=1,#tabl-1 do
local ran = math.random(i,#tabl)
tabl[i],tabl[ran] = tabl[ran],tabl[i]
end
end
Now that we have everything that we need, let’s test it out and look at the output:
Isn’t that just wonderful?
If we use this method to randomize maps for each round, all the maps will appear in order and no maps will be repeatedly appearing.
Let’s create a step variable to walk through the table and when it reaches the end of the table, the table will re-shuffle itself.
math.randomseed(tick())
local nums = {1,2,3,4,5}
local function Shuffle(tabl)
for i=1,#tabl-1 do
local ran = math.random(i,#tabl)
tabl[i],tabl[ran] = tabl[ran],tabl[i]
end
end
local step = 0
while true do
step = step + 1
print(nums[step])
if step == #nums then
Shuffle(nums)
print("Table re-shuffled!")
step = 0
end
wait(1)
end
And we’re finished! Have fun randomizing maps or items without getting too many duplicates.