Skip to content

Instantly share code, notes, and snippets.

@omochi omochi/perm_recur.c
Created Dec 6, 2012

Embed
What would you like to do?
順列列挙でステップごとのメモリ確保無しでできると教わったのでやってみた
//$ 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
You can’t perform that action at this time.