-
Notifications
You must be signed in to change notification settings - Fork 0
/
031.c
97 lines (73 loc) · 1.76 KB
/
031.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Investigating combinations of English currency denominations.
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isLastPerm(int perm[]);
void makePerm(int i, int perm[], int units[]);
void printPerm(int *perm);
int units[] = {200, 100, 50, 20, 10, 5, 2};
int perm[7] = {0};
int i = 0;
int rev_i;
while (true) {
makePerm(i, perm, units);
printPerm(perm);
while (perm[6] != 0) {
perm[6]--;
printPerm(perm);
if (isLastPerm(perm)) {
return 0;
}
}
for (rev_i = 6; perm[rev_i] == 0; rev_i--) {
}
perm[rev_i]--;
i = rev_i + 1;
};
return 0;
}
// Checks whether end condition is met
bool isLastPerm(int perm[]) {
for (int i = 0; i < 7; i++) {
if (perm[i] != 0) {
return false;
}
}
return true;
}
// Generates permutation starting with unit index i
void makePerm(int i, int perm[], int units[]) {
int amountLeft(int *perm, int *units, const int limit);
int maxCoinsIn(const int value, const int sum);
int amount_left;
while ((amount_left = amountLeft(perm, units, 200)) > 0 &&
i < 7) {
perm[i] = maxCoinsIn(units[i], amount_left);
i++;
}
}
// Returns maximum number of coins with value to make sum
int maxCoinsIn(const int value, const int sum) {
return (int)sum / value;
}
// Returns amount left until limit of a permutation
int amountLeft(int *perm, int *units, const int limit) {
int sum = 0;
for (int i = 0; i < 7; i++) {
sum += *perm * *units;
perm++;
units++;
}
return limit - sum;
}
// Prints permutation
void printPerm(int *perm) {
static int count = 0;
count++;
printf("%3i: ", count);
for (int i = 0; i < 7; i++) {
printf("%i ", *perm);
perm++;
}
printf("\n");
}