Randomize numbers in Lua without repeating

I am doing a project in Lua that includes random numbers without repetition. Here is my code

for i = 1, 86000 do
    while rndom[num] ~= nil do
        num = math.random(1,95000)
     end
     rndom[num] = num
     for k=1, 11 do
        file2:write(input[num][k], " ")
     end
     file2:write("\n")
end

This basically sets the value to rndom [num], so when the randomized number is repeated and rndom [num] ~ = nil, it will randomize the number again. My problem is that it takes too long to load, as my "i" gets higher, and there will come a time when it stops. I assume that the randomizer cannot get rndom [num], which is "nil". I mean, what are the odds? I would like to improve the working time. Who can offer a better solution to my problem?

Thank!

+5
source share
2 answers

It is better to generate a permutation with time complexity O(N).

local n = 95000

local t = {}
for i = 1, n do
   t[i] = i
end

for i = 1, 86000 do
   local j = math.random(i, n)
   t[i], t[j] = t[j], t[i]
   for k = 1, 11 do
      file2:write(input[t[i]][k], " ")
   end
   file2:write"\n"
end
+4

random , , , . , O(N^2) ().

+1

All Articles