Created
June 23, 2023 11:10
-
-
Save bogdanq/5cbb1a6883b89deb2395e149d62f3e7a to your computer and use it in GitHub Desktop.
Задачи собеседований, банкомат, atm
This file contains hidden or 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
const atm = (sum, limits) => { | |
const nominals = Object.keys(limits) | |
.map(Number) | |
.sort((a, b) => a - b) | |
const balance = Object.entries(limits).reduce((acc, [key, value]) => acc + key * value, 0) | |
if (sum > balance) { | |
return 'Не достатоно денег' | |
} | |
const result = {} | |
while (nominals.length) { | |
const nominal = nominals.pop() | |
const availableNominalCount = limits[nominal] | |
const needNominalCount = Math.floor(sum / nominal) | |
const nominalCount = Math.min(availableNominalCount, needNominalCount) | |
if (sum >= nominal) { | |
sum = sum - nominal * nominalCount | |
nominals[nominal] -= nominalCount | |
result[nominal] = nominalCount | |
} | |
} | |
if (sum > 0) { | |
return 'Банкомат не может выдать такой номинал' | |
} | |
return result | |
} | |
atm(100, { | |
100: 1, | |
1000: 2, | |
5000: 1, | |
}) // => { '100': 1 } | |
atm(50, { | |
100: 1, | |
1000: 2, | |
5000: 1, | |
}) // => Банкомат не может выдать такой номинал | |
atm(3900, { | |
100: 10, | |
500: 10, | |
1000: 20, | |
5000: 10, | |
}) // => { '100': 4, '500': 1, '1000': 3 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment