Edit: @steven4547466 has a much better method, they fixed a flaw in mine that I hadn’t spotted.
Your method of using a while loop to check if they are the same is good, and we will keep that part. However, the rest of it all needs to be in a loop too, so we can have a sequence of whatever length we like. I would also suggest putting it in a function (it’s the sort of thing that gets more than once). First off, we can define our function and it’s parameters - we need a length, a minimum and a maximum - and the return format: a table. I’d also suggest using types (and therefore strict mode), but that’s up to you.
--!strict
local function UniqueNumberSequence(Length: number?, Minimum: number?, Maximum: number?): {number}
end
Then we need the defaults for the parameters, these can be whatever you want but I’ll use 2, 0 and 5 respectively.
Length = Length or 2
Minimum = Minimum or 0
Maximum = Maximum or 5
Next up is our internal variables, we only need one - to put the return sequence in. We will use table.create()
since it is easier on the computer to assign memory space and we know the exact length of the table. Length also needs a type assertion (since it can be nil
but we know it isn’t)
local Sequence: {number} = table.create(Length :: number)
Now we need a loop to go over the whole length of the sequence. Length needs another type assertion.
for Index: number = 1, Length :: number do
end
To calculate the numbers, we need to choose a random value:
local RandomNumber: number = math.random(Minimum, Maximum)
Then, we need to compare it with the other values that are already in the sequence and change it if that number has already appeared. This can be done nice and easily using table.find()
and a while
loop (just like what you already have).
while table.find(Sequence, RandomNumber) do
RandomNumber = math.random(Minimum, Maximum)
end
After that loop, we know that the number must be unique so we can add it to the Sequence
table.
Sequence[Index] = RandomNumber
Excellent! We now have all the code required to generate a sequence of unique numbers, all we need to do is return what we calculated:
return Sequence
Final Code:
--!strict
local function UniqueNumberSequence(Length: number?, Minimum: number?, Maximum: number?): {number}
Length = Length or 2
Minimum = Minimum or 0
Maximum = Maximum or 5
local Sequence: {number} = table.create(Length :: number)
for Index: number = 1, Length :: number do
local RandomNumber: number = math.random(Minimum, Maximum)
while table.find(Sequence, RandomNumber) do
RandomNumber = math.random(Minimum, Maximum)
end
Sequence[Index] = RandomNumber
end
return Sequence
end