So, the goal is to divide an array of players roughly equally into 4 parts. Below I’ve drawn a diagram of what this might look like.
The natural thing to do is to divide the array into quarters as shown with the green arrows. Unfortunately 4 here doesn’t evenly divide the 9 players. The next best thing to do would be to move each green arrow left a bit. The teams formed by using these shifted arrows are the zig-zag underlines. These will not differ by more than one because without the shift they are all equal. And with the shift between zero to one is subtracted from each.
Of course, we could have chosen any fractions (not just quarters) so this process would work dividing teams into however many parts.
Below I’ve attached some code which does the exact process I’ve described. I’ve generalised it to work for any number of teams; you’ll want to call makeTeams(4).
local function makeTeams(k)
local players = game.Players:GetPlayers()
local n = #players
shuffle(players)
local teams = {}
for i = 1, k do
local team = {}
local lo = math.floor((i-1) * n / k) + 1
local hi = math.floor(i * n / k) + 1
for j = lo, hi-1 do
table.insert(team, players[j])
end
table.insert(teams, team)
end
return teams
end
Here the variables lo and hi compute the positions of shifted arrows by multiplying n (the number of players) by the fraction. Rounding down is the shift operation.
You’ll note there’s a shuffle function which I’ve added. I’ve assumed you don’t want the same teams repeated over and over so to prevent this, I’ve randomly shuffled the players array before dividing. The algorithm I’ve lifted to implement this shuffle is the Fisher-Yates shuffle below.
local function shuffle(array)
local n = #array
for i = 1, n-1 do
local j = math.random(i, n)
array[i], array[j] = array[j], array[i]
end
end
Thanks for reading and I hope this has helped!