# Team Generation?

I’m trying to make a function that generates teams. It takes in # players per team and adds a player to a team that isn’t full. If there are no open spots on a team then create a new team and add the player.

Desired output:
A dictionary of players in teams.

``````local teams = {
[1] = {
"Player1",
"Player2"
},

[2] = {
"Player3",
"Player4"
}
}
``````

What I’ve tried out:

``````local teams = {}
function generateTeams()
local plrsPerTeam = roundType.playersRequired --> 2, 3, 4 etc

for _, player in pairs(playersWaiting) do

for _, team in pairs(teams) do -- problem: teams is empty
local playersInTeam = #team

if playersInTeam < plrsPerTeam then
print("inserting player")
table.insert(team, player)
else
print("inserting team")
table.insert(teams, #teams)
generateTeams()
end
end

end
end
``````

I’m not entirely sure what the best way to do this is. I couldn’t find a post about generating teams other than dividing players into 2 teams.

Thanks.

1 Like
``````local function generateTeams(plrs --[[table]], plrsPerTeam --[[number]])
local numOfPlrs = #plrs
local numOfTeams = math.ceil(numOfPlrs/plrsPerTeam)
local teams = table.create(numOfTeams)
for i = 1, numOfTeams do
local team = table.create(plrsPerTeam)
for i2 = 1, plrsPerTeam do
local plrIndex = (i-1)*plrsPerTeam+i2
if plrIndex > numOfPlrs then
break
end
team[i2] = plrs[plrIndex]
end
teams[i] = team
end
return teams
end``````
2 Likes

Thank you! I couldn’t figure this out for a couple hours.

didn’t even know table.create() existed, I was allocating space by inserting “team”… i
haha ty.

2 Likes