Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / C++

Implementing Permutation Variations

Rate me:
Please Sign up or sign in to vote.
4.75/5 (17 votes)
14 Jul 2004CPOL3 min read 81.5K   857   25  
Several enhanced permutation algorithms created in iterative or recursive solution.
/* http://www.geocities.com/permute_it/sjt_algo.html

   let a[] represent an arbitrary list of objects to permute
   let N equal the length of a[]
   create an integer array p[] of size N+1 to control the iteration     
   initialize p[0] to 0, p[1] to 1, p[2] to 2, ..., p[N] to N
   initialize index variable i to 1
   while (i < N) do {
      decrement p[i] by 1
      if i is odd, then let j = p[i] otherwise let j = 0
      swap(a[j], a[i])
      let i = 1
      while (p[i] is equal to 0) do {
         let p[i] = i
         increment i by 1
      } // end while (p[i] is equal to 0)
   } // end while (i < N)
*/

#include <vector>
using namespace std;

vector<string> example_02(const char* sz)
{
   char a[32];
   strcpy(a, sz);
   int N = strlen(a);   // constant index ceiling (a[N] length)
   int ax = N - 1;   // constant index ceiling (a[N] length)
   int *p = new int[N+1];       // target array and index control array
   int i, j, tmp; // index variables and tmp for swap

   for(i = 0; i < N+1; i++)   // p[N] > 0 controls iteration and the index boundary for i
      p[i] = i;

   vector<string> v;
   v.insert(v.end(), a);      

   i = 1;   // setup first swap points to be ax-1 and ax respectively (i & j)
   while(i < N)
   {
      p[i]--;                // decrease index "weight" for i by one
      j = ax - i % 2 * p[i]; // IF i is odd then j = ax - p[i] otherwise j = ax
      i = ax - i;            // adjust i to permute tail (i < j)

//     if (a[j]!=a[i])
     {
      tmp = a[j];            // swap(a[i], a[j])
      a[j] = a[i];
      a[i] = tmp;

      v.insert(v.end(), a);      
     }

     i = 1;                 // reset index i to 1 (assumed)
      while (!p[i])          // while (p[i] == 0)
      {
         p[i] = i;           // reset p[i] zero value
         i++;                // set new index value for i (increase by one)
      } // while(!p[i])
   } // while(i < N)

   delete []p;
   return v;
} // example_02()

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions