Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive permutation generator for characters [duplicate]

Possible Duplicate:
generate strings with all permutation of character

I am beginner in c++, and I really need your help. I am doing program for permutation using recursion. Here is my code but output is strange, there are same numbers repeating many times and spaces. I could not find out what the problem is or maybe i need to add smth more. Please help me. Here is my code:

#include <iostream>
using namespace std;
#define swap(x,y,t)  ((t)=(x), (x)=(y), (y)=(t))
void perm(char *list, int i, int n);

int main(){
    char a[4]={'a','b','c'};
    perm(a,0,3);
    //cout<<a<<endl;    
    return 0;
}

void perm(char *list, int i, int n){
    int j, temp;
    if (i==n){
        for (j=0; j<=n; j++)
            printf("%c", list[j]);
        printf("     ");
    }
    else {
        for (j=i; j<=n; j++){
            swap(list[i],list[j],temp);
            perm(list,i+1,n);
            swap(list[i],list[j],temp);
            cout<<list<<endl;
        }
    }
}
like image 853
bionian Avatar asked Nov 12 '22 21:11

bionian


1 Answers

The function is correct but you are not calling it correctly.

perm(a,0,3);

should be

perm(a,0,2);

Why?

Your for loop:

for (j=i; j<=n; j++){

goes till n, so n should be a valid index.

Works fine

like image 183
codaddict Avatar answered Nov 15 '22 11:11

codaddict