Quote:
ok, i need a fast function to assign permutations of n objects uniqely to integers.
|
If you sort your inital sequence into lexicographical order, then you already have your index, from order (0) -> reverse order (N!-1).
This is what next_permutation is doing anyway

... it just gives the next lexicographical permutation.
The only challenge is to go from index -> permutation and back again, if you need it (I kind of assumed this).
Recursive functions, to coin a phrase, really bake my noodle, but
I think that you are basically doing this already in your second code sample.
However, there is a clear explanation of this on comp.programming -
http://tinyurl.com/6nzj6 (googlegroups) and I don't think I would do it justice to try and re-interpret it here. The author states O(N^2), rather than O(N), but see implementation note at the bottom, and uses a non-recursive function (loop <---> recursive anyway, no?)
For:
a) Depends - are you using lots of different sequences or just one? how long are they? In my opinion, generally I enumerate as much as possible given that memory is cheap and my patience thin, but also how much efficiency is a genuine concern (to be honest.
very rarely, beyond practical constraints, for me) over a working algorithm.
b) If you need it, I imagine that proof of a unique lexicographical order is available on google ... ask a friendly mathematician ... I still don't quite understand why "because it looks like it should" doesn't count as proof *sigh*
Bear in mind that I don't have (much) formal education in CS or Maths, mostl of the stuff I know is derived from empirical experience, so I hope this isn't shooting too low for you.
Anyway, HTH - even if it doesn't. it was an interesting read for me
