I'm not sure what the question is about. Basically, it looks like you are looking for a way to "encode" a permutation by an integer. But it is not clear whether this encoding is required to be synchronized with permutation sequence generated by sequential calls to std::next_permutation
. Is it? I.e do you require that number 176791
encodes a permutation produced by 176791
applications of std::next_permutation
?
Permutations can be encoded by integers in several different ways. Properly constructed encodings will all occupy the same number of bits. But different encodings will might use different integers to encode the same permutation.
Anyway, if you don't care about a specific encoding method, then any permutation for N
elements can be encoded in the following manner:
Imagine the canonical representation of the permutation: an array of N
indexes that describe the new positions of the sequence's elements, i.e. index[old position] = new position
.
Now simply interpret that array as a N-digit number in base N
. I.e. the permutation is represented by an integer value
index[0]*N^0 + index[1]*N^1 + index[2]*N^2 + ... + index[N-1]*N^(N-1)
Basically, the canonical array representation of the original permutation is packed into a sufficiently large integer value. (If N
is a power of 2, this representation will simply pack the original array values into a bit-array). Both packing and unpacking is a straightforward process.
Unfortunately, the representation I describe above is not well-constructed. It requires more bits than necessary, since it attempts to "losslessly" encode index
arrays with non-unique values. A valid representation of a permutation will not have repetitive values in the index array. This immediately means that the above representation is excessive. A more compact representation should be possible. Anyway, this should be a rather well-researched subject and a simple Google search should turn up lots of information on encoding permutations.
Here's a SO link that offers a much deeper analysis of this topic
Fast permutation -> number -> permutation mapping algorithms