2

I have a function which takes six octal (0-7) digits as an argument and returns true or false.

I would like to run a loop that tries every single permutation of the values 0-7, and counts the number of "true" returns.

something like:

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

I've tried playing around with the examples provided in http://www.lua.org/pil/9.3.html but those are all about iterating over tables, not quite what I'm doing.

I don't necessarily care about performance, this function is to test the compare function I wrote.

Is there an easy way to loop something until all possible permutations are tried?

ridthyself
  • 821
  • 1
  • 8
  • 19
  • Do you mean actual permutations of chars '0' - '7', where in a permutation each char appears exactly once? Or all arrays of six octal digits are ok? – mpeterv Jan 09 '14 at 20:50
  • 2
    Also, the linked PiL chapter has exactly the function you need. You can put octal digits in an array and then pass it to the 'permgen' function to get the iterator. – mpeterv Jan 09 '14 at 21:00
  • I haven't thought of it that way, I believe you are right. – ridthyself Jan 10 '14 at 12:26

1 Answers1

3

The straightforward method would seem fine, given the stated requirements:

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

Of course, this has nothing to do with permutations. I favored the conflicting requirement (as seen in the question asker's code) that the first parameters are 0,0,0,0,0,0.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72