Click to See Complete Forum and Search --> : Is there a better way to permutate a string?


erxuan
February 8th, 2003, 01:08 PM
Q: Write a function to print all of the permutations of a string.

A: I wrote a recursive function to fulfill this. I was wondering if there's a better way to do this? either simpler or having less Runtime...
Thanks!

#include <string.h>
#include <iostream.h>
/*Remove one character from str*/
void strrmv(const char *str, char* newstr,int removethis)
{
for (int i=0; i<removethis; i++){
*(newstr+i)=*(str+i);
}
for(int i=removethis+1; i<strlen(str); i++){
*(newstr+i-1)=*(str+i);
}
*(newstr+i-1)='\0';
}

void permuString(char *a, int size)
{

if (size==1){
cout<<a<<endl;
return;
}
else
{
for (int i=0; i<size; i++)
{
cout << a[i];
char *temp= new char[size];
strrmv(a,temp,i);
permuString(temp, size-1);
delete temp;
}
}
}



void main()
{
char instr[]="abcd";
int l = strlen(instr);
permuString(instr,l);
}


//p.s.: what's the best way to create an array dynamicly according to the input? Should I use new, delete? or should I use vector?

Wfranc
February 8th, 2003, 06:04 PM
Check the msnd online please, I think there is something similar for you to take alook at. It is nice also:D




Best Regards,:)

Paul McKenzie
February 8th, 2003, 08:55 PM
Originally posted by erxuan
Q: Write a function to print all of the permutations of a string.

You mean this?

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

void PrintPermutation(char *p)
{
cout << p << endl;
int nLen = strlen(p);
while (next_permutation(p, p + nLen))
cout << p << endl;
}

int main()
{
char p[] = "ABC123";
PrintPermutation(p);
return 0;
}

If you're wondering, next_permutation() is an STL <algorithm> function that does what you want.

Regards,

Paul McKenzie