-
-
Save aldraco/bb6063e7be48d5c972ec to your computer and use it in GitHub Desktop.
// @N is the amount you are making change for | |
// @coins is the set of coin values you can use | |
function makeChange(N, coins) { | |
// initialize the 'ways' array | |
var answers = []; | |
for (var n = 1; n <= N; n++) { | |
answers[n] = 0; | |
} | |
// there is only one way of doing 0 cents? | |
// this is initialized for the first pass through of the problem | |
answers[0] = 1; | |
// go through the coins one at a time | |
coins.forEach(function(coin){ | |
// test each value after you are able to use at least one of the coin | |
for (var i = coin; i <= N; i++) { | |
// can you make change from the remainder | |
// after subtracting out another coin? | |
var rem = i - coin; | |
answers[i] += answers[rem]; | |
} | |
}); | |
// answers at the amount will be the sum of all possibilities | |
return answers[N]; | |
} |
Credit to Charilaos Skiadas from the Scala Functional Programming course on Coursera - found this in the forums to help understand how this function can work recursively.
Here's how I approached the problem:
The question is in how many ways can we add our change to C, while using denominations a1, a2, a3, ..., an provided by a list.
Well, we will either use an a1 or we will not.
If we do, then now we have C-a1 left, and still using the denominations a1, a2, a3, ..., an. This would be a recursive call to our function, with C-a1 as the amount and the same list of denominations.
If we don't, then now we still have C as the amount, but can only use the denominations from a2 and on (the tail of the list). This is again a recursive call. The ways of doing this are all distinct from the ways that 3 gives us, since those were using the a1 and these are not.
The sum of the counts from 3 and 4 would be the number of ways we are after. The only thing left is to take care of edge cases, so that the recursive calls terminate. I think those were outlined well in the above posts but I'll repeat them:
If the amount is negative, then we've tried to use too many coins. This is not a viable way, so the answer would be 0.
If there are no more denominations left (list empty). Then if the amount left is 0 we've found a viable way, and we want to count it by returning 1, otherwise it's another dead-end since we have no more coins left, and we would return 0.
Challenge here: https://www.hackerrank.com/challenges/coin-change
Dynamic programming