Click here to Skip to main content
12,762,236 members (39,246 online)
Click here to Skip to main content

Stats

70K views
813 downloads
25 bookmarked
Posted 12 Jul 2004

Implementing Permutation Variations

, 14 Jul 2004 CPOL
Several enhanced permutation algorithms created in iterative or recursive solution.
// ============================================================================
// File:   EnhPerRe.cpp - Testing RecPermutation
// Author: Zuoliu Ding, May 2004
// ============================================================================
#include <string>
#include <vector>
using namespace std;

// ============================================================================
// Function:    RecPermutation - Enhanced Permutation Recursion
// Description: Generate all Permuted strings for an input string
// Parameter:   sz:   [in] an input string.
//              bRepeated: [in] Allow element repeated or not
// Return:      A vector of all Permuted strings.
// ============================================================================
vector<string> RecPermutation(const char* sz, 
                              bool bRepeated)
{
   vector<string> v, v1;
   string s1;    char ch;
   int nLen = strlen(sz);      

   if (nLen==1)            // Base case: Add one-char string
      v.insert(v.end(), sz);      
   else                    // nLen > 1, need recursion
   {
      for (int i=0; i<nLen; i++)
      {
         ch = sz[i];       // Extract each char as the first

         // To exclude repeated element
         if (!bRepeated)
         {
            for (int j=0; j<i; j++)
               if (ch==sz[j]) break;

            if (j<i) continue;   // If i==j, Not a repeated one
         }

         s1 = sz;           // Copy the original string
         s1.erase(i, 1);    // Put the rest string into s1

         v1 = RecPermutation(s1.c_str(), 
                        bRepeated); // Recursive 

         for (int i=0; i < (int)v1.size(); i++)
         {
            s1 = ch + v1[i];   
            v.insert(v.end(), s1);   
         }
      }
   }

   return v;
}

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)

Share

About the Author

Zuoliu Ding
Software Developer
United States United States

You may also be interested in...

Pro
Pro
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 15 Jul 2004
Article Copyright 2004 by Zuoliu Ding
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid