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

How do I make a pair of math.random() generated numbers not repeat itself?

Asked by 8 years ago
Edited 8 years ago

I have a very successful mini-game script part that I've worked on which is:

1function InsertColor()
2    for i, v in pairs (game.Players:GetPlayers()) do
3    local PlayerColor = Instance.new("Color3Value")
4    PlayerColor.Parent = v.Character
5    PlayerColor.Name = "Color"
6    PlayerColor.Value = Color3.new(math.random(), math.random(), math.random())
7    TweenColorScreen()
8    end
9end

Each player would be given a random color: eg: 200, 8, 15 which would be a red dominant color

Out of the thousands of permutations possible, how do I make someone in one game not have the same color as someone else so that there could be only one winner?

Thank You.

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

First off I would like to say it is important to include the following at the top of your script:

1math.randomseed(os.time());

This makes the random numbers even more random.

Then add this: (sorry for weird formatting, I am typing this in web browser and not in an editor)

So basically what you wanna do is store all the random colors in a table, and when you generate a color, you want to check and see if it is already in use.

01local colors = {};
02 
03function IsInTable(Table,Item)
04    for i = 1, #Table, 1 do
05        if (Table[i] == Item) then
06            return true;
07        end
08    end
09    return false;
10end
11 
12function GenrateRandomColor()
13    local color = Color3.new(math.random(),math.random(),math.random());
14    while true do
15        if (IsInTable(colors,color) then
View all 33 lines...

EDIT: I left out a wait(); at line 14 because it is unlikely you will need to iterate more than once to find a unique random color.

So recap:

- Use math.randomseed(os.time()) to ensure your numbers are actually random

- In the extremely unlikely case that a player will get the same three multi digit / decimal random numbers as someone else, keep track of all the colors and check whether or not it has been used yet, if so generate a new one and repeat.

0
If the color is going to be used on bricks, some extra work will be needed to disambiguate between colors, because Color3 values are collapsed to some BrickColor approximations - i.e. two Color3's which are different could lead to the same BrickColor. duckwit 1404 — 8y
1
You forgot to add a 'wait' yield inside your iteration @Line 14 RoyallyFlushed 19 — 8y
0
@sunwatt Good catch, but I left it out because it is highly unlikely that you will need to iterate more than once to generate a new random number plasma_node 343 — 8y
0
If you want your colors to be bright: local color = Color3.fromHSV(math.random(), 1, 1) l_owbar 1 — 8y
Ad

Answer this question