I am using permutation to generate a string (using each of its character) into “helloworld!”, however it took…176791 to get to “helloworld!” Is there a ways so I can just input: 176791 to quickly permutate to “helloworld!”?
...
176790. helloworl!d
176791. helloworld!
My code:
#include <windows.h>
#include <string>
#include <iostream>
#include <algorithm>
int main( void )
{
::UINT64 Count = 0;
std::string SomeString = "eohldo!lwrl";
do
{
Count ++;
std::cout << Count << ". " << SomeString << std::endl;
if( SomeString == "helloworld!" )
break;
} while( std::next_permutation( SomeString.begin( ), SomeString.end( ) ) );
::getchar( );
return( 0 );
};
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 number176791encodes a permutation produced by176791applications ofstd::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
Nelements can be encoded in the following manner:Imagine the canonical representation of the permutation: an array of
Nindexes 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 valueBasically, the canonical array representation of the original permutation is packed into a sufficiently large integer value. (If
Nis 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
indexarrays 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