表格的值没有改变。

我有一个二维数组,所有单元格都填充了零。

我正在尝试做的是选择一些随机选择的单元格并使用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
点赞
用户869951
用户869951

我不确定 for i=1,fp 循环在处理 tempfo 的时候在做什么,例如种子应该只设置一次,而且在 local 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
2014-06-22 18:34:16