c permutation of a number

Posted by Pkp on Stack Overflow See other posts from Stack Overflow or by Pkp
Published on 2012-03-31T04:09:37Z Indexed on 2012/03/31 5:29 UTC
Read the original article Hit count: 139

Filed under:
|

I am writing a program for magic box. As the only way around it is brute force, I wrote a program to compute permutations of a given array using bells algorithm. I wrote in the lines similar to http://programminggeeks.com/c-code-for-permutation/.

It does work for array of 3 and 4. It does not work for an arryay of 8 numbers (1,2,3,4,5,6,7,8). I see that the combination 1 2 3 4 5 6 7 8 gets repeated couple of times. Also there are other combinations that gets repeated. I see that certain combinations don't get displayed even. So could someone tell me what is wrong in the program below.

Code:

include<stdio.h>

int len,numperm=1,count=0;

display(int a[]){
int i;
for(i=0;i<len;i++)
printf("%d ",a[i]);
printf("\n");
count++;
}

swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}

no_of_perm(){
int x;

for(x=1;x<=len;x++)
   numperm=numperm*x;
}

perm(int a[]){
int x,y;
while(count < numperm){
  for(x=0;x<len-1;x++){
    swap(&a[x],&a[x+1]);
    display(a);
  }
 swap(&a[0],&a[1]);
    display(a);

  for(y=len-1;y>0;y--){
    swap(&a[y],&a[y-1]);
    display(a);
  }

  swap(&a[len-1],&a[len-2]);
    display(a);
}


}


main(int argc, char *argv[]){

if(argc<2){
  printf("Error\n");
  exit(0);
}

int i,*a=malloc(sizeof(int)*atoi(argv[1]));

len=atoi(argv[1]);
for(i=0;i<len;i++)
  a[i]=i+1;

no_of_perm();
perm(a);

}

© Stack Overflow or respective owner

Related posts about c

    Related posts about permutation