Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to select several random players?

Asked by 3 years ago

Hello! So I'm trying to make a system that randomly chooses several players to be inserted into a table. Say I want to put 10 players into a table randomly, how do I do that? (It can't select the same player twice)

I've tried to do this:

local Players = game:GetService("Players")

local Murderers = {}
local Civilians = {}

function AssignTeams()
    local Player = Players:GetPlayers()

    repeat
        table.insert(Murderers, Players[math.random(1, #Players)])
        table.insert(Civilians, Players[math.random(1, #Players)])
    until #Murderers == 2 and #Civilians == 10

end

AssignTeams()

Even if it does works, I want to find a more efficient (if possible, more effective) way to do this. Cheers!

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

Not sure if it is 'efficient' or 'effective'

local Players = game:GetService("Players")

local Murderers = {}
local Civilians = {}

function AssignTeams()
    local Player = Players:GetPlayers()
    local playersnotyetselected = {}
    for i, v in pairs(Player) do
        table.insert(playersnotyetselected,i,v)

    end

    repeat
    local plr = playersnotyetselected[math.random(1, #playersnotyetselected)]
        table.insert(Murderers,1, plr)
    table.remove(playersnotyetselected,table.find(playersnotyetselected,plr))

    until #Murderers == 2 
    for i, v in pairs(playersnotyetselected) do
        table.insert(Civilians, i,v)
    end
end

AssignTeams()

table.find returns the index if the obj is found but if not then nil

0
I edited my answer. I just released I had to do the table,index,value on table.insert AProgrammR 398 — 3y
0
Alright, thank you! I can finally sleep in peace. NotThatFamouss 605 — 3y
0
:GetPlayers gives you table copy, you can modify that imKirda 4491 — 3y
0
@imKirda Oh, ok. AProgrammR 398 — 3y
Ad

Answer this question