I therefore developed a simple, fast and yet non-recursive method;
thats useful especially when working on the graphics card with CUDA as recursion is not possible there.
Expand|Select|Wrap|Line Numbers
- std::string default = "12345";
- int perm=1, digits=default.size();
- for (int i=1;i<=digits;perm*=i++); // perm = !default.size()
- for (int a=0;a<perm;a++)
- {
- std::string avail=default; // initialize string
- // b counts the columns
- for (int b=digits,div=perm;b>0; b--)
- {
- // compute the number of repetitions for one character in the actual column
- div/=b;
- //compute the index of the character in the string
- int index = (a/div)%b;
- printf("%c", avail[index] );
- //remove the used character
- avail.erase(index,1) ;
- }
- printf("\n");
- }
- printf("permutations:%d\n",perm);