Last active
May 14, 2020 17:41
-
-
Save DeaconDesperado/adb24a1c13d712a0f30c24c47a009c49 to your computer and use it in GitHub Desktop.
MakeChange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//For a given dollar amount (as an integer 100 == $1) compute all combinations of coins | |
//that can make even change | |
let changePermutations = (v, coinDenominations) => { | |
let subCombinations = (accum, sumAccum, total, coins) => { | |
//Base case: there's no coins left to try or remaining coins would take us beyond zero | |
if(coins.length == 0 || total < 0) return accum; | |
//This coin being attempted reduces to zero, making even change | |
if(total == 0) return accum.concat([sumAccum]); | |
//Recurse step: | |
//One stack trying the next denomination without removing the current one | |
//Another stack removing current step's denomination from rolling total and proceeding with all denominations | |
return subCombinations(accum, sumAccum, total, coins.slice(1)).concat( | |
subCombinations(accum, [coins[0]].concat(sumAccum), total - coins[0], coins) | |
) | |
} | |
return subCombinations([],[],v,coinDenominations) | |
} | |
changePermutations(100, [1,5,10,25,50,100]).forEach(x => console.log(x)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment