How do I randomize half of the players in the server?

So for the system I’m doing, I have to get half of the players in-game. How would I do this? All I know is that I would have to use some sort of table and loop through the players.

local half = {}
local otherHalf = {}

for _, v in pairs(game.Players:GetPlayers()) do
        -- ???
end
3 Likes

Even though this might not be the most efficient way here it goes.

First of all, we are going to get all the players.

local Players = game:GetService("Players") --//Gets the Players

And then start setting up a for loop so you can get the players

local ChosenPlayers = {} --//A table containing chosen players

for i = 1, #Players/2, 1 do --//Setting a for loop which is supposed to run the code block written below amount of Players / 2 times
	local RandomNumber = math.random(1,#Players) --//Getting a random number from 1 to amount of players
	local Player = Players[RandomNumber] --//Getting the player with the random number from the Players table
	table.remove(Players, RandomNumber) --//Removing the chosen player from our players table
	table.insert(ChosenPlayers,Player) --//Adding the chosen player into a table which we will store all the chosen players in
end
3 Likes
local players = game:GetService("Players")

for i, player in pairs(players:GetPlayers()) do
	if i % 2 == 0 then --checks if player number is divisible by 2 without a remainder
		--do something with player
	end
end

Much simpler & more efficient way of producing the same behavior.

1 Like

If I’m not mistaken that wouldn’t be random, it’d just get the same players over and over if no one leaves or joins the server.

Here is me running the same code 4 times in a row, no one left or joined the server meanwhile.
image
The same thing works out with the second player as wellimage

local players = game:GetService("Players")
local playerList = players:GetPlayers()

for i = 1, #playerList/2 do
	local rand = math.random(1, #playerList)
	local plr = playerList[rand]
	--do stuff with player
end

This should be truly random.

1 Like

And, that is the exact thing I sent more or less.

Less lines of code, no table manipulation.

I get you want less lines of code however how are you gonna store the chosen half of the players? And how are you gonna stop it from chosing the same person over and over again?

This will help split the players into 2 halves:

local Players = game:GetService("Players")

local Half_1 = {}
local Half_2 = {}

local Half = 1

for _, player in pairs(Players:GetPlayers()) do
    if Half == 1 then
        table.insert(Half_1, player)
        Half = 2
    elseif Half == 2
        table.insert(Half_2, player)
        Half = 1
    end
end

edit: I have a feeling I know what you are trying to do