Skip to content

Instantly share code, notes, and snippets.

@skimi
Last active September 19, 2019 20:42
Show Gist options
  • Save skimi/d78ebd8469eef647b33794aec1acb099 to your computer and use it in GitHub Desktop.
Save skimi/d78ebd8469eef647b33794aec1acb099 to your computer and use it in GitHub Desktop.
Calculate minimal change for cash
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));
@skimi
Copy link
Author

skimi commented Sep 19, 2019

Failed a test exercice asking for this :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment