Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created April 9, 2014 04:41
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 mlhaufe/10226699 to your computer and use it in GitHub Desktop.
Save mlhaufe/10226699 to your computer and use it in GitHub Desktop.
Greedy Change Making Algorithm
var qapik = [50,20,10,5,3,1],
usCoins = [25,10,5,1];
//denominations (ds) must be in descending order
function makeChange(coins,ds){
var result = {}
for(var i = 0, d = ds[i]; i < ds.length; d = ds[++i]){
result['n'+d] = Math.floor(coins/d) // a div d
coins = coins % d
}
return result
}
makeChange(67,usCoins).toSource() // ({n25:2, n10:1, n5:1, n1:2})
makeChange(67,qapik).toSource() // ({n50:1, n20:0, n10:1, n5:1, n3:0, n1:2})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment