# Loop through RNG without duplicate numbers

Hello there! I’m having trouble trying to go about looping through a math.random number picker, but how can I loop through math.random a couple times without it picking duplicate numbers?

Here is a quick example that I made that of part of the code structure I will be using:

``````for i = 1,12 do
local rng = math.random(1,12)
print(rng)
end``````
``````local randomSamples = {}
for i=1,12 do
randomSamples[i] = i
end

for i=1,12 do
local randomPick = table.remove(randomSamples, math.random(1, #randomSamples))
print("My random number: ", randomPick)
end
``````

or if you want to like to shuffle cards

``````function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end

local randomSamples = {}
for i=1,12 do
randomSamples[i] = i
end
shuffle(randomSamples)

for i=1,12 do
local randomPick = table.remove(randomSamples, #randomSamples)
print("My random number: ", randomPick)
end
``````
4 Likes

Insert 1 of every number you want possibly generated into a table, shuffle the table, then remove from the end.

Alternatively, you can set it as `math.random(#randomSamples)`, if the function only finds one value, it will automatically set it as the maximum and have 1 as the minimum.

I like to explicitly declare the random interval as I find that it helps with code readability, especially when teaching newer programmers. But yes, a singular argument to math.random(n) will automatically declare an interval [1, n]

2 Likes

It worked, but is there a way to make it so if all numbers are already chosen the table will reset back.