I want to generate 10 number out of a table but a number may only be selected one’s.
for i=1,10 do
for k,v in pairs(z2) do
if z2[i]==v then break end
for k,v in pairs(z2) do print(k,v) 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.
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
I need 10 random numbers from 1 to 20 but the numbers may not repeat
I don’t see how this can help me, this only gives me the numbers in random order.
while #tab<10 do
for z=1,#tab do
if tab[z]==r then
if not found then
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, n,…n 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.