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

Math.random how to make it not pick the same string?

i'm trying to make it get a random string but sometimes they both pick the same string how can I prevent that?

	local Power= {"Earth", "Fire", "Lightning", "Water"}
	Player.Power.Element1.Value = Power[math.random(1, #Power)]
	Player.Power.Element2.Value = Power[math.random(1, #Power)]

1 answer

✓ Accepted answer

Every math.random without a seed uses the same seed, and this creates the same result. To fix this, you can use Random.new().

local rand = Random.new(tick()) -- tick makes the seed different with every game launch
local Power= {"Earth", "Fire", "Lightning", "Water"}
Player.Power.Element1.Value = Power[rand:NextInteger(1, #Power)]
Player.Power.Element2.Value = Power[rand:NextInteger(1, #Power)]

EDIT:

local rand = Random.new(tick()) -- tick makes the seed different with every game launch
local Power= {"Earth", "Fire", "Lightning", "Water"}
Player.Power.Element1.Value = Power[rand:NextInteger(1, #Power)]

repeat -- Prevent the second value from being the same
	Player.Power.Element2.Value = Power[rand:NextInteger(1, #Power)]
until Player.Power.Element2.Value ~= Player.Power.Element1.Value

If there are any errors, please comment.

6 comments

1

is there a chance that it'll pick the same string?

0

There is a small chance, just by random chance. You can implement safeguards against this easily however.

0

Editted to show this process.

0

Aight Thx.

0

Or math.randomseed

0

It's generally better practice to use Random.new().

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