Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

--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

✓ Accepted answer

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)

2 comments

0

ill answer it in a minute just need to wait until i can answer another question xD

0

Ah, thanks.

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

2 comments

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.

0

Using my solution would mitigate that problem because there would only be one player to choose from

This discussion is preserved as it was. New answers, comments, and votes are closed.