Thursday, 15 August 2013

lua - Table value doesn't change -



lua - Table value doesn't change -

i have 2 dim array , it's cells filled zeros.

what i'm trying take randomly chosen cells , fill 4 or 5

but either empty gird value equal 0 or 1 value has changed 4 or 5 , that's code below:

local grid = {} i=1,10 grid[i] = {} j=1,10 grid[i][j] = 0 end end local empty={} i=1,10 j=1,10 if grid[i][j]==0 table.insert(empty,i ..'-'.. j) end end end local fp=math.floor(table.maxn(empty)/3) local fx,fy i=1,fp 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 grid[fx][fy]=4 elseif fo==1 grid[fx][fy]=5 end end i=1,10 j=1,10 print(grid[i][j]) end print('\n') end

i'm not sure for i=1,fp loop doing temp , fo, illustration seed should set once, , also, homecoming value on line after local fo ignored, seems messy. based on post, if want randomly select n cells 2d array , set either 4 or 5 (randomly), should work:

-- maybe n = fp local n = 5 math.randomseed(os.time()) local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] == 0 grid[fx][fy] = math.random(4,5) = + 1 end until > n

note closer n number of items in array (100 in example), longer take loop complete. if concern, big n values, opposite: initialize each cell 4 or 5 randomly, , randomly set size - n of them 0.

math.randomseed(os.time()) local rows = 10 local columns = 10 local grid = {} if n > rows*columns/2 i=1,rows grid[i] = {} j=1,columns grid[i][j] = math.random(4,5) end end local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] ~= 0 grid[fx][fy] = 0 = + 1 end until > n else i=1,rows grid[i] = {} j=1,columns grid[i][j] = 0 end end local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] == 0 grid[fx][fy] = math.random(4,5) = + 1 end until > n end

lua lua-table

No comments:

Post a Comment