2

I have the following code:

wrg = { "1.png", "2.png", "3.png", "4.png" };

table = { }

for i = 1, 4 do
    table[ i ] = wrg[ math.random( 1, #wrg ) ]
end

for i = 1, 4 do
   print( table[ i ] )
end

output:

4.png
2.png
4.png
4.png

I don't need repeat "4.png" how fix?

1 Answer 1

2

You need a random permutation. For instance, this code:

wrg = { "1.png", "2.png", "3.png", "4.png" };
t = {}

n=#wrg
for i=1,n do
    t[i]=wrg[i]
end

math.randomseed(os.time())

for i=1,n-1 do
    local j=math.random(i,n)
    t[i],t[j]=t[j],t[i]
end

for i=1,n do
   print(t[i])
end

Not the answer you're looking for? Browse other questions tagged or ask your own question.