Write a program that will print out all the possible combinations of the charecters present in the given string.for example:monu,numo,nmou etc.

Showing Answers 1 - 5 of 5 Answers

Hello,
See the code below:

#include

#include

using namespace std;

void permute(char *str, int location)
{
if(location == strlen(str)-1)
{
cout << str << "n";
}
for(int j=location; j {
char *str1 = new char[strlen(str)];
strcpy(str1,str);
str1[location] = str1[j];
str1[j] = str[location];
permute(str1,location+1);
}
}
int main(int argc, char *argv[])
{
if(argc <=1 )
{
cout << "n Usage: permute stringn";
return 0;
}
permute(argv[1],0);
return 0;
}

  Was this answer useful?  Yes

disha

  • Jun 30th, 2007
 

void swap(char * arrIn, const int index1, const int index2)
{
    char tmp=arrIn[index1];
    arrIn[index1] = arrIn[index2];
    arrIn[index2] = tmp;
}

void permute(char *str, const int index)
{
    if(index == strlen(str)-1)
    {    cout<<str<<endl;    return;}
    int lenth = strlen(str);
    char *tmp = new char[lenth+1];
    strcpy(tmp, str);
    tmp[lenth] = '';
    permute(tmp,index+1);
    delete[] tmp;
    int i = index+1;
    do
    {
        swap(str, index, i++);
        tmp = new char[lenth+1];
        strcpy(tmp, str);
        permute(tmp,index+1);
        tmp[lenth] = '';
        delete[] tmp;            
    }while(i<lenth);
}
int main(int argc, char* argv[])
{
    char string[] = "number";
    permute(string,0);

    getch();
    return 0;
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions