2013-04-02 158 views
2

任何人都可以幫助我隨機填充N值的表,其中值爲1,...,M允許不重複嗎?隨機表Corona SDK/Lua

乾杯。

+1

然後對您的問題的答案是:「是的,有一種方法可以這樣做。」請檢查[faq#dontask](http://stackoverflow.com/faq#dontask)。 – hjpotter92

+0

我編輯了我的問題。 – Eyeball

+0

相關:http://stackoverflow.com/q/158716 – finnw

回答

4
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 

你所需的表會tFinal。您還可以添加一個條件,其中if M < N then N = M end

+0

非常感謝你! – Eyeball

3

這可能會幫助你...

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 

保持編碼........

+0

感謝您的幫助!我得到它的工作= D – Eyeball