lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,
I just started with lua and checking what the best way is to solve various problems.
My question is about recursive funtions.
Lets say I want to write a function list_perm(n) that will list for me all the permutations of 1,2,...n
First I wrote a function to list all the combinations of the n numbers
The first combination listed should be 1,1,1,...1 the last one should be n,n,n,...n. And in the middle somewhere we should have for example 1,2,3,4,...n
I implemented the well known algorithm (I think it originates from Knuth):

A={}
function Combinations(n,m) for i = 1, n do A[m] = i if (m<n) then Combinations(n,m+1) else
           B=A[1]
for j=2,n do B=B ..", ".. A[j] end print(B)
       end
   end
end
Combinations(4,1)

Combinations (n,1) should be called to start up.
How can I solve the similar problem when I need only the permutations?
Somhow I should be able to make the function remember which numbers did it allready use,
but probably there has to be a better way to do this.
Can anyone help in this?

Szilard