Search code examples
randomluaunique

generate non duplicate integers in Lua


I am trying to generate 5 random non duplicate values between 0,500 and assign them to 5 variables using Lua.

So far I have used the following code which unsuccessfully attempts to generate the random numbers and assigns the values. The problem is:

  1. this code is sometime generating the duplicate numbers
  2. the name which I want to look like x-1, x-2 and so on, prints like x-1, x-12.

Can you please help me with this.

Example:

v_Name = "x-"
for i =1, 5 do
  X = math.random (0, 500)
  v_Name = v_Name..(i)
  print (v_Name)
  print (X)
 end 

Solution

  • Here is a solution, clarified in the comments:

    math.randomseed( os.time() ) -- first, sets a seed for the pseudo-random generator
    
    local  function my_random (t,from, to)  -- second, exclude duplicates
       local num = math.random (from, to)
       if t[num] then  num = my_random (t, from, to)   end
       t[num]=num 
       return num
    end
    
    local t = {}    -- initialize  table with not duplicate values
    local v_Name = "x-"
    for i =1, 5 do
      X = my_random (t, 0, 500)
      v_Name = v_Name .. i    -- It is better to use the table here and concatenate it after..
      print (v_Name, "=" ,X)
     end