-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake-change.js
52 lines (40 loc) · 1.11 KB
/
make-change.js
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
/*
Write a function that, given:
1. an amount of money
2. an array of coin denominations
computes the number of ways to make amount of money with coins of the available denominations.
Example: for amount=4 (4¢) and denominations=[1,2,3] (1¢, 2¢ and 3¢), your program would output 4—the number of ways to make 4¢ with those denominations:
1¢, 1¢, 1¢, 1¢
1¢, 1¢, 2¢
1¢, 3¢
2¢, 2¢
*/
const denominations = [1,2,3];
const makeChange = (amount, denominations) => {
let result = 0;
const subroutine = (running) => {
if (running === amount) {
return result++;
}
if (running > amount) {
return false;
}
return denominations.forEach((item) => {
return subroutine(running + item)
});
}
subroutine(denominations[0]);
return result;
}
const makeChangeTail = (amount, denominations, running) => {
running = running || 0;
if (running === amount) {
return running++;
}
if (running > amount) {
return running;
}
for (let i = 0; i < denominations.length; i++) {
return makeChangeTail(amount, denominations, running + denominations[i]);
}
}