2

谁能帮助我用 N 个值随机填充一个表,其中值是 1,...,M 不允许重复?

干杯。

4

2 回答 2

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

于 2013-04-02T15:16:37.307 回答
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

继续编码…………

于 2013-04-02T15:07:21.623 回答