Last active
August 29, 2015 13:57
-
-
Save lotabout/9658944 to your computer and use it in GitHub Desktop.
print all permutation of a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#include <string.h> | |
/* two solution: | |
* 1. function "perm" | |
* 2. function "print_permutation" | |
*/ | |
void swap(int data[], int a, int b) | |
{ | |
int tmp = data[a]; | |
data[a] = data[b]; | |
data[b] = tmp; | |
} | |
/* [4 1 2 3] => [1 2 3 4] */ | |
void rotate_one_left(int data[], int len) | |
{ | |
int tmp = data[0]; | |
memcpy(data, data+1, (len-1)*sizeof(*data)); | |
data[len-1] = tmp; | |
} | |
void print_data(int data[], int len) | |
{ | |
int i; | |
for (i = 0; i < len; i++) { | |
printf("%d", data[i]); | |
} | |
printf("\n"); | |
} | |
/* this one use no additional space */ | |
void perm(int data[], int len, int level) | |
{ | |
if (level >= len - 1) { | |
print_data(data, len); | |
return; | |
} | |
int i; | |
for (i = level; i < len; i++) { | |
swap(data, i, level); | |
perm(data, len, level + 1); | |
} | |
rotate_one_left(data+level, len-level); | |
} | |
void print_permutation(int data[], int len, const char *prefix) | |
{ | |
if (len <= 0) { | |
printf("%s\n", prefix); | |
return; | |
} | |
int *sub_array= (int *)malloc(len * sizeof(*sub_array)); | |
memcpy(sub_array, data, len*sizeof(*sub_array)); | |
int i, j, k; | |
char new_prefix[BUFSIZ]; | |
for (i = 0; i < len; i++) { | |
sprintf(new_prefix, "%s%d", prefix, data[i]); | |
swap(sub_array, i, 0); | |
print_permutation(sub_array+1, len-1, new_prefix); | |
} | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
int data[] = {1, 2, 3, 4, 5, 6, 7}; | |
/*print_permutation(data, 7, "");*/ | |
perm(data, 7, 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment