Last active
September 19, 2019 20:42
-
-
Save skimi/d78ebd8469eef647b33794aec1acb099 to your computer and use it in GitHub Desktop.
Calculate minimal change for cash
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
var change = (cash) => { | |
var bills = [2, 5, 10]; | |
var change = bills.reduce((carry, bill) => { | |
carry[bill] = 0; | |
return carry; | |
}, {}); | |
var remaining = cash; | |
bills.forEach((bill, index) => { | |
if (index === bills.length - 1) { | |
change[bill] = Math.floor(remaining / bill); | |
remaining -= change[bill] * bill; | |
return; | |
} | |
var restFromNextBill = remaining % bills[index + 1]; | |
while(restFromNextBill && remaining > 0) { | |
change[bill]++; | |
remaining -= bill; | |
restFromNextBill = remaining % bills[index + 1]; | |
} | |
}); | |
if (remaining !== 0) { | |
return null; | |
} | |
return change; | |
} | |
console.log(change(60 + 11)); | |
console.log(change(60 + 6)); | |
console.log(change(9000000000000000 + 11)); | |
console.log(change(42)); | |
console.log(change(6)); | |
console.log(change(3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Failed a test exercice asking for this :(