Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do you randomize a for i,v in pairs loop?

Asked by 6 years ago

So, basically, I have this module script that, whenever called, it creates a set of teams and assigns players to them. However, it utilizes a for i,v in pairs loop to do this, which means the teams aren't really random at all. Simply because it inserts v (The player) into a table and always runs that same table every time the function is called. If my understanding is correct, that is.

01local module = {}
02 
03local TS = game:GetService("Teams")
04 
05function module.Teams(MC)
06    local GT,YT = Instance.new("Team",TS),Instance.new("Team",TS)
07    GT.TeamColor,YT.TeamColor = BrickColor.new("Lime green"),BrickColor.new("New Yeller")
08    GT.Name,YT.Name = "Green","Yellow"
09    GT.AutoAssignable,YT.AutoAssignable = false,false
10    for i,v in pairs(game.Players:GetPlayers()) do
11        if i % 2 == 0 then
12            v.TeamColor = BrickColor.new("Lime green")
13        else
14            v.TeamColor = BrickColor.new("New Yeller")
15        end
16        wait()
17    end
18end
19 
20return module

Basically what this does is;

4 Players in the game

Function is called

Green Team and Yellow Team are created

Player 1 is inserted into Yellow Team

Player 2 is inserted into Green Team

Player 3 is inserted into Yellow Team

Player 4 is inserted into Green Team

Function is called again

Repeats the same process

What I'm trying to figure out is how to randomize that to where maybe the first time it's called, Player 1 and Player 2 are on the same team, Player 3 and Player 4 on the other. Then, when called again, Player 2 and Player 3 are on the same team and Player 1 and Player 4 are on the same team. I want it to always be random. How would I accomplish this?

1 answer

Log in to vote
1
Answered by
Vmena 87
6 years ago
Edited 6 years ago

You would have to send all the values into a table and then randomize that table.

Randomizing an array can be quite tricky but the fisher-yates shuffle algorithm is efficient and should work just fine. https://en.wikipedia.org/wiki/Fisher–Yates_shuffle

Here's the code:

01function shuffle(array)
02    local ShuffledArray = { }
03    local random = math.random
04 
05    for index = 1, #array do
06        local offset = index - 1
07        local value = array[index]
08        local randomIndex = offset*random()
09        local flooredIndex = randomIndex - randomIndex%1
10 
11        if flooredIndex == offset then
12            output[#output + 1] = value
13        else
14            output[#output + 1] = output[flooredIndex + 1]
15            output[flooredIndex + 1] = value
View all 37 lines...

Glad I could help!

Ad

Answer this question