Created
September 26, 2017 17:08
-
-
Save batogov/d5d0ae49afb4cf833074fd3c90667ad7 to your computer and use it in GitHub Desktop.
ATM
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
function comp(a, b) { | |
return b - a; | |
} | |
function atm(total, values) { | |
values = values.sort(comp); | |
let counts = {}; | |
let success = true; | |
while (total > 0 && success) { | |
for (let i = 0; i < values.length; i++) { | |
if (values[i] <= total) { | |
if (counts.hasOwnProperty(values[i])) { | |
counts[values[i]] += 1; | |
} else { | |
counts[values[i]] = 1; | |
} | |
total -= values[i]; | |
break; | |
} else if (i === values.length - 1) { | |
success = false; | |
} | |
} | |
} | |
if (success) { | |
return counts; | |
} else { | |
return false; | |
} | |
} | |
function hardAtm(total, valuesMap) { | |
let counts = {}; | |
let success = true; | |
let valuesArr = []; | |
for (value in valuesMap) { | |
let sameValues = Array(valuesMap[value]).fill(parseInt(value)); | |
valuesArr = valuesArr.concat(sameValues); | |
} | |
values = valuesArr.sort(comp); | |
while (total > 0 && success) { | |
for (let i = 0; i < values.length; i++) { | |
if (values[i] <= total) { | |
if (counts.hasOwnProperty(values[i])) { | |
counts[values[i]] += 1; | |
} else { | |
counts[values[i]] = 1; | |
} | |
total -= values[i]; | |
values.splice(i, 1); | |
break; | |
} else if (i === values.length - 1) { | |
success = false; | |
} | |
} | |
} | |
if (success) { | |
return counts; | |
} else { | |
return false; | |
} | |
} | |
const total = 5665; | |
const values = [5000, 1000, 500, 100, 50, 10, 5]; | |
const shuffledValues = [5, 10, 5000, 500, 50, 100, 1000]; | |
const valuesMap = { | |
'5000': 2, | |
'1000': 1, | |
'500': 2, | |
'10': 10, | |
'5': 5 | |
} | |
console.log(atm(total, shuffledValues)); | |
console.log(hardAtm(total, valuesMap)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment