MCPcopy Create free account
hub / github.com/careercup/CtCI-6th-Edition-JavaScript / coins

Function coins

chapter08/8.11 - Coins/coins.js:3–46  ·  view source on GitHub ↗
(value, currCoin)

Source from the content-addressed store, hash-verified

1var dp = {};
2
3var coins = function(value, currCoin) {
4 if (currCoin === undefined) {
5 currCoin = 1;
6 }
7 if (value < 0) {
8 return 0;
9 } else {
10 var key = `${value}:${currCoin}`;
11 if (dp[key] === undefined) {
12 if (value === 0) {
13 dp[key] = 1;
14 } else {
15 var ways = 0;
16 if (currCoin <= 1) {
17 ways += coins(value - 1, 1);
18 }
19 if (currCoin <= 5) {
20 ways += coins(value - 5, 5);
21 }
22 if (currCoin <= 10) {
23 ways += coins(value - 10, 10);
24 }
25 if (currCoin <= 25) {
26 ways += coins(value - 25, 25);
27 }
28 /*
29
30 added provision if half dollars and dollar coins are added,
31 but that would be unamerican.
32
33 if (currCoin <= 50) {
34 ways += coins(value - 50, 50);
35 }
36 if (currCoin <= 100) {
37 ways += coins(value - 100, 100);
38 }
39
40 */
41 dp[key] = ways;
42 }
43 }
44 return dp[key];
45 }
46};
47
48/* TEST */
49// there is 1 way to represent 0 cents

Callers 1

coins.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected