Skip to content

Instantly share code, notes, and snippets.

@omochi
Created December 6, 2012 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omochi/4226356 to your computer and use it in GitHub Desktop.
Save omochi/4226356 to your computer and use it in GitHub Desktop.
順列列挙でステップごとのメモリ確保無しでできると教わったのでやってみた
//$ gcc -std=m9 perm.c
#include<stdio.h>
#include<stdlib.h>
void swap_int(int *a,int *b){
int t = *a;
*a = *b;
*b = t;
}
void print_int_array(int array[],int num){
printf("[ ");
for(int i=0;i<num;i++)printf("%d ",array[i]);
printf("]\n");
}
void print_int_array_u(int array[],int num,void *user){
print_int_array(array,num);
}
void perm_iter(int items[],int numItems,int depth,void (*callback)(int array[],int num,void *user),void *user){
if(depth >= numItems){
(*callback)(items,numItems,user);
return;
}
for(int i=depth;i<numItems;i++){
swap_int(&items[depth],&items[i]);
perm_iter(items,numItems,depth+1,callback,user);
swap_int(&items[depth],&items[i]);
}
}
int main(int argc,char *argv[]){
int *array = NULL;
if(argc<=1){
printf("usage : %s a[0] a[1] a[2] ...\n",argv[0]);
exit(1);
}
array = malloc(sizeof(int)*(argc-1));
for(int i=1;i<argc;i++){
array[i-1] = atoi(argv[i]);
}
perm_iter(array,argc-1,0,&print_int_array_u,NULL);
free(array);
array=NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment