Balancing equally into X other tables

I’ve been working on a menu where you can select your team before the lobby starts, however if you don’t choose one, it automatically sorts you into the team with the least number
(Please note this isn’t using default roblox teams, it’s using metatables, I’ve removed the metatable formatting/methods since it’s not relevant here)(Plrs is defined earlier as the players in the default team)

local LowestTeam = 99999
local LowestTeamName = ""
	
for _, V in Plrs do
	for i, v in Teams do
		if i == DefaultTeamName then continue end
			
		if #v <= LowestTeam then
			LowestTeam = #v
			LowestTeamName = i
		end
	end

	ChangeTeam(V, LowestTeamName)
end

I figured something like this would work, but it doesn’t, and only ever goes with the team that STARTED with the least, it’s not name clash, and I’ve verified it is in fact getting the players within the teams

Distributing equally between multiple tables is easy, but since I need to balance players from JUST the default team into the other teams while maintaining roughly equal player-count between them

Anyone know what I did wrong? I would’ve thought my original method would work, but it obviously has something wrong with it

this should work

print the team table (v) inside the loop and count the players manually to see if its working

Can’t tell from the code posted, but if v is a dictionary rather than an array then the # operator wont work on it.

1 Like

Your LowestTeam and LowestTeamName variables are defined too far upscope, so they’re re-used for each player. Since the variables still contain the data from the prior iteration, if no other team has the same number of players as the team that was selected during the first iteration, the system will keep adding players to that first team. All you need to do is move the variable declarations inside the first loop:

for _, V in Plrs do

	local LowestTeam = 99999
	local LowestTeamName = ""

	for i, v in Teams do
		if i == DefaultTeamName then continue end
			
		if #v <= LowestTeam then
			LowestTeam = #v
			LowestTeamName = i
		end
	end

	ChangeTeam(V, LowestTeamName)
end
1 Like

oh true, I use the player as the index so that would be the case wouldn’t it be

1 Like

that’s not the case, since the amount already chosen won’t change between iterations, and the name isn’t used in the logic of picking the team, so the scope of those variables won’t really change much(I originally had it inside the loop, but moving it changed nothing)