CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2002
    Posts
    18

    Question 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.

  2. #2
    Join Date
    Mar 2002
    Location
    AhuhA
    Posts
    204

    Smile

    Check the msnd online please, I think there is something similar for you to take alook at. It is nice also




    Best Regards,

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    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
  •  





Click Here to Expand Forum to Full Width

Featured