2014-01-09 18 views
2

我有一個函數,它需要六個八進制數(0-7)作爲參數並返回true或false。編寫一個循環,當每次置換都被嘗試結束時

我想運行一個循環,嘗試值0-7的每個單一排列,並計算「真實」返回的數量。

類似:

function count_possibles() 
local count=0 
local a,b,c,d,e,f=0,0,0,0,0,0 
while possiblepermutations > 0 do 
    if compare(a,b,c,d,e,f) == true then count = count +1 end 
    permute(a,b,c,d,e,f) 
    possiblepermutations = possiblepermutations -1 
return count 
end 

我已經試過玩弄於http://www.lua.org/pil/9.3.html提供的例子,但這些都是關於遍歷表,不太我在做什麼。

我不一定關心性能,這個函數是測試我寫的比較函數。

有沒有簡單的方法來循環的東西,直到所有可能的排列嘗試?

+0

你的意思是字符'0' - '7'的實際排列,在一個置換中每個字符只出現一次?或者六個八進制數字的所有數組都可以嗎? – mpeterv

+2

另外,鏈接的PiL章節恰好具有您需要的功能。你可以在數組中放八進制數字,然後將它傳遞給'permgen'函數來獲取迭代器。 – mpeterv

+0

我還沒有這樣想過,我相信你是對的。 – ridthyself

回答

3

的直接的方法似乎很好,給出的規定要求:

local count = 0 
local total = 0 
for a = 0, 7 do 
    for b = 0, 7 do 
     for c = 0, 7 do 
      for d = 0, 7 do 
       for e = 0, 7 do 
        for f = 0, 7 do 
         total = total + 1 
         if compare(a,b,c,d,e,f) == true then count = count +1 end 
        end 
       end 
      end 
     end 
    end 
end 
return count, total 

當然,這有沒有關係排列。我贊成衝突的要求(如問題提供者代碼所示),第一個參數是0,0,0,0,0,0。

相關問題