-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10063_knuths_permutation_2.c
77 lines (62 loc) · 1.92 KB
/
10063_knuths_permutation_2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Author: Chen Rushan
* E-Mail: [email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define MAX_STR_LEN 12
int fact[MAX_STR_LEN + 1];
void
generate_all_knuth_perm(char *str, int len)
{
int i = 0, j = 0, k = 0;
char used[MAX_STR_LEN] = {};
char newstr[MAX_STR_LEN] = {};
for (i = 0; i < fact[len]; i++) {
int num = i;
memset(used, 0, sizeof(used));
/* generate a knuth permutation at index @num
*/
for (j = len; j >= 1; j--) {
int idx = num % j;
/* find the position to put str[j - 1]
*/
for (k = 0; k < len; k++) {
if (used[k] == 1)
continue;
if (idx != 0) {
idx--;
continue;
}
newstr[k] = str[j - 1];
used[k] = 1;
break;
}
/* the index of knuth permutation for str[0, j - 2]
*/
num /= j;
}
printf("%s\n", newstr);
}
}
int
main(int argc, char **argv)
{
char str[MAX_STR_LEN];
int len = 0, i = 0, blank = 0;
fact[0] = 1;
for (i = 1; i <= MAX_STR_LEN; i++)
fact[i] = fact[i - 1] * i;
while (1) {
if (scanf("%s", str) == EOF)
break;
len = strlen(str);
if (blank)
putchar('\n');
blank = 1;
generate_all_knuth_perm(str, len);
}
return 0;
}