Last active
April 25, 2020 20:21
-
-
Save gm50x/b91225bba89edf54a15be66e359270cb to your computer and use it in GitHub Desktop.
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
/** | |
* PROBLEM: Change | |
* You are writing a change calculating algorithm that will | |
* determine the proper change with the smallest possible amount | |
* of coins and bills. | |
* For the problem, consider you have: | |
* - Bills: 100, 50, 20, 10, 5 and 2 | |
* - Coins: 1, 0.5, 0.25, 0.10, 0.05 and 0.01 | |
* | |
* Enough talk... Get coding! | |
* | |
*/ | |
function findMax(amount) { | |
const money = [100, 50, 20, 10, 5, 2, 1, 0.5, 0.25, 0.10, 0.05, 0.01] | |
.map(p => normalizePrecision(p)) | |
.sort((a, b) => a > b) | |
return money.find(p => p <= amount) | |
} | |
function normalizePrecision(n, type = 'UP') { | |
return type === 'UP' ? n * 100 : n / 100 | |
} | |
function calculateChange(n) { | |
let change = [] | |
n = normalizePrecision(n) | |
while (n) { | |
let amount = findMax(n) | |
change.push(amount) | |
n = n - amount | |
} | |
return change.map(p => normalizePrecision(p, 'DOWN')) | |
} | |
let changes = [7.84, 123.99, 250, 3.2] | |
changes.forEach(change => console.log( | |
`Your change is: ${change.toFixed(2).padStart(6, ' ')}\t> ${calculateChange(change).reduce((acc, val) => acc + val + '\t', '')}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment