Could anyone help me with a way to randomly fill a table with N values, where the values are 1,...,M allowing no duplicates ?
Cheers.
Could anyone help me with a way to randomly fill a table with N values, where the values are 1,...,M allowing no duplicates ?
Cheers.
local M, N, tNonFinal, tFinal = 500, 20, {}, {}
math.randomseed( os.time() )
for i = 1, N, 1 do
local iRandom = math.random(1, M)
while tNonFinal[iRandom] do
iRandom = math.random(1, M)
end
table.insert( tNonFinal, iRandom, true )
tFinal[i] = iRandom
end
Your required table will be tFinal
. You can also add a condition where if M < N then N = M end
This may help you...
local myArray = {}
local valueArray = {1,2,3,4,5,6,7,8,9,10} -- let it be the array with values 1,2...M
local index = 0
local isFetched = {}
for i=1,#valueArray do
isFetched[i] = 0
end
local randomValue = 0
local function addTomyArray()
randomValue = math.random(#valueArray)
if(isFetched[randomValue]==0)then
index = index + 1
isFetched[randomValue] = 1
myArray[index] = valueArray[randomValue]
if(index==#valueArray)then
for i=1,#myArray do
print(myArray[i]) -- result : shuffled array
end
end
else
addTomyArray()
end
end
timer.performWithDelay(0,addTomyArray,#valueArray) -- #valueArray
Keep coding........