Recursive character permutation generator

Possible duplicate:
generate lines with all permutation of characters

I am starting in C ++ and I really need your help. I am using a recursive permutation program. Here is my code, but the output is strange, repeated many times and spaces. I could not understand 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;
        }
    }
}
+5
source share
1 answer

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

perm(a,0,3);

it should be

perm(a,0,2);

Why?

Your for loop:

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

goes to n, so it nmust be a valid index.

Works great

+1
source

All Articles