随机表Corona SDK / Lua

时间:2013-04-02 14:20:36

标签: random lua corona lua-table

任何人都可以帮我一个随机填充N值表的方法,其中值为1,...,M不允许重复?

干杯。

2 个答案:

答案 0 :(得分: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

的条件

答案 1 :(得分: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

继续编码........