Lua 表值不变

Lua 表值不变,lua,lua-table,Lua,Lua Table,我有一个2维的数组,所有的单元格都是零 我想做的是随机选取一些单元格,用4或5填充 但我得到的要么是所有值都等于零的空网格,要么只有一个值变为4或5,这是我下面的代码: local grid = {} for i=1,10 do grid[i] = {} for j=1,10 do grid[i][j] = 0 end end local empty={} for i=1,10 do for j=1,10 do

我有一个2维的数组,所有的单元格都是零

我想做的是随机选取一些单元格,用4或5填充

但我得到的要么是所有值都等于零的空网格,要么只有一个值变为4或5,这是我下面的代码:

     local grid = {}
  for i=1,10 do
    grid[i] = {}
    for j=1,10 do
      grid[i][j] = 0
    end
  end

  local empty={}
  for i=1,10 do
    for j=1,10 do
      if grid[i][j]==0 then
        table.insert(empty,i ..'-'.. j)
      end
    end
  end
  local fp=math.floor(table.maxn(empty)/3)
  local fx,fy
  for i=1,fp do

    math.randomseed(os.time())
    math.random(0,1)
    local fo=math.random(0,1)
    math.random(table.maxn(empty))
    local temp= empty[math.random(table.maxn(empty))]
    local dashindex=string.find(temp,'-')

     fx=tonumber(string.sub(temp,1,dashindex-1))
     fy=tonumber(string.sub(temp,dashindex+1,string.len(temp)))
    if fo==0 then
      grid[fx][fy]=4
    elseif fo==1 then
      grid[fx][fy]=5
    end
end


for i=1,10 do
  for j=1,10 do
    print(grid[i][j])
  end
  print('\n')
end
我不确定for I=1,fp循环对temp和fo做了什么,例如seed应该只设置一次,而且,忽略本地fo之后的行上的返回值看起来非常混乱。但是,根据您的帖子,如果您真的只想从2D数组中随机选择N个单元格,并将其随机设置为4或5,那么这应该是可行的:

-- maybe N = fp
local N = 5
math.randomseed(os.time())
local i = 1
repeat
    fx = math.random(1, 10)
    fy = math.random(1, 10)
    if grid[fx][fy] == 0 then
        grid[fx][fy] = math.random(4,5)
        i = i + 1
    end
until i > N
但是请注意,在您的示例中,N越接近数组100中的项数,循环完成所需的时间就越长。如果这是一个问题,那么对于较大的N值,可以执行相反的操作:将每个单元格随机初始化为4或5,然后随机将大小-N设置为0

math.randomseed(os.time())

local rows = 10
local columns = 10
local grid = {}

if N > rows*columns/2 then 
    for i=1,rows do
        grid[i] = {}
        for j=1,columns do
            grid[i][j] = math.random(4,5)
        end
    end

    local i = 1
    repeat
        fx = math.random(1, 10)
        fy = math.random(1, 10)
        if grid[fx][fy] ~= 0 then
            grid[fx][fy] = 0
            i = i + 1
        end
    until i > N

else
    for i=1,rows do
        grid[i] = {}
        for j=1,columns do
            grid[i][j] = 0
        end
    end

    local i = 1
    repeat
        fx = math.random(1, 10)
        fy = math.random(1, 10)
        if grid[fx][fy] == 0 then
            grid[fx][fy] = math.random(4,5)
            i = i + 1
        end
    until i > N
end

当我调试我的代码时,我得到了正确的结果,但当我运行它时,我没有得到正确的结果,我每次都打印出fx和fy,并且每次都得到相同的结果math.randomsedos.time不能在一个周期内。就在你代码的开头。谢谢@EgorSkriptunoff,但我也试着用i乘以os.time,这是我的工作。我每次都得到相同的值。正如Egor告诉你的那样,你不能在循环中播种RNG。为RNG设定种子是一个初始化步骤。如果继续初始化它,它将始终返回相同的值。谢谢@Scholli的回答,这是有效的,但我不知道为什么有时我每次运行代码时都会得到相同的结果相同的随机值可能是IDE现金值,或者我不知道为什么会得到这样的结果,对于第二个解决方案,不,在我的case@Tony如果您希望每次运行时随机数相同,您需要将seed设置为您选择的某个常量,并进行web搜索以了解如何选择好的seed,但是像7861231这样的任意值应该可以。