2014-06-19 40 views
2

我有一個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 
+0

當我調試我的代碼我得到一個正確的結果 ,但是當我運行它我不打印,每次我打印出fx和fy,並且我得到它們每次都是一樣的 – Tony

+0

'math.randomseed(os.time())'must not在一個週期內。只是在你的代碼的開始。 –

+0

謝謝@EgorSkriptunoff,但我也試圖乘以os.time,它的工作我每次都得到相同的值 – Tony

回答

1

我不知道什麼for i=1,fp循環與tempfo做,例如種子應該只設置一次,而且,返回local fo之後的線值被忽略,看起來很亂。但根據您的文章,如果你真的只是想隨機從您的二維數組選擇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 
+0

感謝@Scholli爲你的答案是工作,但我不知道爲什麼有些時候我得到了相同的結果每次我運行該代碼相同的隨機值也許IDE現金一些價值,或者我不知道爲什麼我喜歡這個結果和對於第二個解決方案不,它不起作用在我的情況下 – Tony

+0

@Tony如果你想讓隨機數字在你每次運行時都是相同的,你需要將種子設置爲你選擇的某個常量(做一個網絡搜索選擇好的種子,但像7861231這樣的任意值應該沒問題)。 – Schollii