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

How do I make sure the same player doesn't get picked twice when using math.random on a table?

Asked by
LawlR 182
6 years ago
--Not the full script

local Players = {}
local Zombies = {}
for i,v in pairs(players:GetPlayers()) do
    table.insert(Players,v.Name)
end
table.insert(Zombies ,(Players[math.random(#Players)]))

Depending on how many players there are, a certain amount of players get chosen to be zombies. The problem I am facing is that sometimes the same player gets chosen twice. How would I prevent this?

2 answers

Log in to vote
1
Answered by
thebayou 441 Moderation Voter
6 years ago

All you have to do is just remove the player from the table once they're chosen.

local chosenPlayerIndex = math.random(#Players)
table.insert(Zombies, Players[chosenPlayerIndex])
table.remove(Players, chosenPlayerIndex)
0
ill answer it in a minute just need to wait until i can answer another question xD misterviggo 61 — 6y
0
Ah, thanks. LawlR 182 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

thebayou has a working way, otherwise u can make a variable with the last player that got choosen and then a if function that checks if the last player is the same as the one that got choosed before and if it did you just randomize again

0
Yeah, but the problem with this is that it can sometimes cause lag once enough players are chosen. For example, if it's a huge 50 player server and everybody but one is a zombie, that would require the last person to be chosen randomly which could take very long because if the script chooses any of the other players it'll have to re-choose. thebayou 441 — 6y
0
Using my solution would mitigate that problem because there would only be one player to choose from thebayou 441 — 6y

Answer this question