Antwan
Antwan

Reputation: 3876

Table value doesn't change

I have a 2 dim array and all it's cells filled with zeros.

What i'm trying to do is to take some randomly chosen cells and fill it with 4 or 5

but what i get is either empty gird with all value equal to zero or i get just one value that has changed to 4 or 5 and that's my code below:

     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

Upvotes: 2

Views: 80

Answers (1)

Oliver
Oliver

Reputation: 29453

I'm not sure what the for i=1,fp loop is doing with temp and fo, for example the seed should only be set once, and also, the return value on line after local fo is ignored, seems very messy. But based on your post, if you really just want to randomly select N cells from your 2D array and set those to either 4 or 5 (randomly), this should work:

-- 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

Note however that the closer N is to number of items in array (100 in your example), the longer it will take for the loop to complete. If this is a concern, then for large N values, you could do the opposite: initialize each cell to 4 or 5 randomly, and then randomly set size - N of them to 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

Upvotes: 1

Related Questions