String Permutation Challenge

Problem

Here is another mathematical problem, where the trick is as much to discover the algorithm as it is to write the code: write a program to display all possible permutations of a given input string--if the string contains duplicate characters, you may have multiple repeated results. Input should be of the formpermute string
and output should be a word per line.

Here is a sample for the
input 
catcat 
cta 
act 
atc 
tac 
tca

Solution

#include <iostream>
#include <string>

using namespace std;

string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute(string topermute, int place)
{
if(place == topermute.length() - 1)
{
cout<<topermute<<endl;
}
for(int nextchar = place; nextchar < 
    topermute.length(); nextchar++)
{
permute(swtch(topermute, place, nextchar),
        place+1);
}
}

int main(int argc, char* argv[])
{
if(argc!=2)
{
cout<<"Proper input is 'permute string'";
                return 1;
}
        permute(argv[1], 0);
}

Comments