Tuesday, 4 March 2014

Permutations using Coroutines in Lua

First let's look at the algorithm for Permutations using recursion

algorithm Permutation(array, count)
              if array index is 0, display the array

              for each item in array until count
                     swap last and first item                    
                     Permutation(array, count -1)
                     swap last and first item                    
              end
end

now the code

function permuterate (a, n)
      if n == 0 then
        --printResult(a)
        coroutine.yield(a)
      else
        for i=1,n do

        --print("iteration=", i, "n=", n, "last=", a[n], "i th=",a[i])
          -- put i-th element as the last one
          a[n], a[i] = a[i], a[n]

          -- generate all permutations of the other elements
          permuterate(a, n - 1)

          --print("i=", i, "n=", n, "last=", a[n], "i th=",a[i])
          -- restore i-th element
          a[n], a[i] = a[i], a[n]

        end
      end
end

function printResult (a)
    for i,v in ipairs(a) do
        io.write(v, " ")
    end
    io.write("\n")
end

function createPermuterate(list)
    local pick = table.getn(list)
    local co = coroutine.create(function () permuterate(list, pick) end)

    return function()
                local _, value = coroutine.resume(co)

                return value
            end
end

function createPermuterate1(list)
    local pick = table.getn(list)
    return coroutine.wrap(function () permuterate(list, pick) end)
end

for p in createPermuterate{"1","2","3";n=3} do
    printResult(p)
end

for p in createPermuterate1{1,2,3;n=3} do
    printResult(p)
end

No comments: