|
-
February 8th, 2003, 02:08 PM
#1
Is there a better way to permutate a string?
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!
Code:
#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?
Last edited by erxuan; February 8th, 2003 at 02:10 PM.
-
February 8th, 2003, 07:04 PM
#2
Check the msnd online please, I think there is something similar for you to take alook at. It is nice also
Best Regards,
-
February 8th, 2003, 09:55 PM
#3
Re: Is there a better way to permutate a string?
Originally posted by erxuan
Q: Write a function to print all of the permutations of a string.
You mean this?
Code:
#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
Last edited by Paul McKenzie; February 8th, 2003 at 10:02 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|