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;
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With