Skip to content

Instantly share code, notes, and snippets.

@timruffles
Created May 17, 2016 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timruffles/8d5a2d8143dd85fad21e0fd7a8420e0e to your computer and use it in GitHub Desktop.
Save timruffles/8d5a2d8143dd85fad21e0fd7a8420e0e to your computer and use it in GitHub Desktop.
(tail) recursive solution to giving change
"use strict";
/**
* The function will use a Greedy method to solve the problem of giving
* change.
*
* @param {Integer} the amount for which we have to give change
* @param {Array} the values of the coins that are available
*
* @return {Array} the list of the selected coins, sorted ascending by value,
* or an empty array if impossible
*/
function coinChange (amount, coins) {
// sort coins outside recursive step
coins.sort((a,b) => b - a);
return recursiveCoinChange(amount, coins, []);
}
function recursiveCoinChange(amount, coins, used) {
if(coins.length === 0) {
return amount > 0 ? [] : used.reverse();
}
const biggest = coins[0];
// first coin won't fit...
if(amount < biggest) {
coins.shift();
// ...so new sub-problem doesn't consider it
return recursiveCoinChange(amount + 0, coins, used);
// ...or if it will
} else if(amount >= biggest) {
used.push(biggest);
// use it - we reduce the amount and store and coin
return recursiveCoinChange(amount - biggest, coins, used);
} else {
// otherwise we're done! no coin will fit
return used.reverse();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment