Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Q: Write a function to print all of

Status
Not open for further replies.

erxuan

Programmer
Feb 7, 2003
3
US
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 j=0; j<size; j++)
{
cout << a[j];
char *temp= new char[size];
strrmv(a,temp,j)
permuString(temp, size-1);
delete temp;
}
}
}



void main()
{
char instr[]=&quot;abcd&quot;;
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?
 
I'd figure new and delete would work fine for this, not a whole lot of memory allocation, or storage of items going on..
And as for recursion, that's the overhead.. if you did it without recursion, it'd run less bloaty (possibly) but however, it's less code to do it without the recursion definately The weevil of doooooooooom
-The eagle may soar, but the weasel never gets sucked up by a jet engine (Anonymous)
 
oops, I mean less code to do it with the recursion, dang just waking up! The weevil of doooooooooom
-The eagle may soar, but the weasel never gets sucked up by a jet engine (Anonymous)
 
#inlcude<string>
using std::string;
and use STL strings. You will find there all the needed functionality. Ion Filipski
1c.bmp


filipski@excite.com
 
With STL this is a piece of cake..

Code:
#include <string>
#include <iostream>
#include <algorithm>

using std::cout;
using std::endl;

int main()
{
 std::string test = &quot;abcd&quot;;
 std::string temp = test;
 std::sort(temp.begin(), temp.end()); // string must be sorted
 while(std::next_permutation(temp.begin(), temp.end()))
  cout << temp << endl;
 return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top