How to make half of the things on a table do something?

I want to make Half the Players on a team switch to another team.

The issue is that I don’t know how to make Exactly Half of the players do something
The script I have tried is

for i,v in pairs(game.Players:GetPlayers()) do
    if i % 2 == 0 then
        v.Team = game.Teams.Blue
    else
        v.Team = game.Teams.Red
    end
end

This makes all the players have a 50% chance of switching the team. I want only half the players to have a 100% chance of switching teams.
plz help

Shuffle the array of players randomly, then split it down the middle.

You may also want to look at the first example at the bottom of this page, which seems to keep teams balanced as players join/leave. Not exactly you’re question but maybe useful.

Edit: found this shuffle algorithm:

function FYShuffle( tInput )
    local tReturn = {}
    for i = #tInput, 1, -1 do
        local j = math.random(i)
        tInput[i], tInput[j] = tInput[j], tInput[i]
        table.insert(tReturn, tInput[i])
    end
    return tReturn
end

So your algorithm just becomes

local players = game.Players:GetPlayers()
local shuffled = FYShuffle(players)

Then put the players in the first half of shuffled on one team and the rest on the other team.

1 Like