Random number from table not repeat

I want to generate 10 number out of a table but a number may only be selected one’s.

Tried this

function randomNumber()
    z={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
    z2={}
    for i=1,10 do 
    z2[i]=math.random(1,#z)
      for k,v in pairs(z2) do
        if z2[i]==v then break end
      end
    end
    
  table.insert(z2,z2[i])
  for k,v in pairs(z2) do print(k,v) end
    
end

Do a forum search for random numbers. The code has already been written for this.

You aren’t really after random numbers, you are wanting to randomly shuffle your table.

http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

To shuffle an array a of n elements (indices 0…n-1):
for i from n ? 1 downto 1 do
j ? random integer with 0 ? j ? i
exchange a[j] and a[i]

Don’t have time to lua that up, but it should be pretty simple

Edit: read it again, and I’m not quite right, but you could do the above shuffle and then just take the first 10.

Maybe TLL should add a table.randomize(table) function.

The Fisher-Yates-Knuth algorithm has already been coded here on the forums. Here’s one example: http://codea.io/talk/discussion/3079/like-a-turned-card/p1

Ah, thank you @LoopSpace

I need 10 random numbers from 1 to 20 but the numbers may not repeat
ex. 5,12,10,6,9,11,12,18,20,4

I don’t see how this can help me, this only gives me the numbers in random order.

Try this.


function setup()
    print(table.concat(rand()," "))
end

function rand()
    local tab={}
    while #tab<10 do
        local r=math.random(20)
        local found=false
        for z=1,#tab do
            if tab[z]==r then
               found=true
            end
        end
        if not found then
            table.insert(tab,r)
        end       
    end
    return(tab)
end

the reason that sorting works is that it gives you a list of numbers in random order.

If you want ten random numbers, then you just take the first ten numbers from the list, ie n[1], n[2],…n[10] where n is the list.

This is very efficient, and the code is worth keeping for use in other projects.

Yes, thanks i got it. both Work fine. Thanks for the help.