Created
October 5, 2017 15:49
-
-
Save unilecs/f3a81200273cc492dac464f7166ca953 to your computer and use it in GitHub Desktop.
Task about giving cash from 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 giveMyMoney(money, coins) { | |
let needCoins = [], minCoins = []; minCoins[0] = 0; | |
// перебираем все суммы до заданной суммы (можно начать с мин.купюры) | |
for (let sum = 1; sum <= money; sum++) { | |
// по умолчанию эта сумма не для выдачи | |
minCoins[sum] = Number.MAX_VALUE; | |
// перебираем все купюры | |
for (let coin = coins.length - 1; coin >= 0; coin--) { | |
if (sum >= coins[coin].val && minCoins[sum] > minCoins[sum - coins[coin].val] + 1) { | |
// нашли способ выдать сумму sum | |
minCoins[sum] = minCoins[sum - coins[coin].val] + 1; | |
} | |
} | |
} | |
// Если заданную сумму нельзя разложить по заданным купюрам | |
if (minCoins[money] === Number.MAX_VALUE) { return []; } | |
// minCoins - хранит минимальное кол-во купюр, ктр нужны для выдачи заданной суммы | |
let sum = money; | |
while (sum > 0) { | |
let curSum = sum; | |
for (let coin = coins.length - 1; coin >= 0; coin--) { | |
let isCoinExist = coins[coin].count > 0; | |
if (isCoinExist && sum >= coins[coin].val && (minCoins[sum] == minCoins[sum - coins[coin].val] + 1 || minCoins[sum] == minCoins[sum - coins[coin].val])) { | |
if (!needCoins[coin]) { | |
needCoins[coin] = 0; | |
} | |
++needCoins[coin]; | |
sum -= coins[coin].val; | |
coins[coin].count -= 1; | |
break; | |
} | |
} | |
if (curSum === sum) { | |
needCoins = []; | |
break; // не хватает купюр | |
} | |
} | |
return needCoins; | |
} | |
let coins = [ | |
{ val: 30, count: 10 }, | |
{ val: 50, count: 10 }, | |
{ val: 100, count: 10 }, | |
{ val: 500, count: 10 }, | |
{ val: 1000, count: 10 }, | |
{ val: 5000, count: 10 } | |
]; | |
const money = 19890; | |
const needCoins = giveMyMoney(money, coins); | |
let res = "", controlSum = 0; | |
if (needCoins.length) { | |
needCoins.forEach((item, ind) => { | |
controlSum += item*coins[ind].val; | |
const symbol = ind < needCoins.length-1 ? " + " : ""; | |
res += (item + "*" + coins[ind].val + symbol); | |
}); | |
} | |
console.info(res ? `Control sum ${controlSum} must be the same as input sum ${money}!`: ""); | |
console.info(res ? `${money} = ${res}` : "Введена неверная сумма или недостаточно купюр в банкомате"); |
Your solution has a mistake
You have to iterate from left to right
line 28: for (let coin = 0; coin < coins.length; coin++)
@maranqz, now it works
Not working for:
let coins = [
{ val: 20, count: 10 },
{ val: 150, count: 2 },
{ val: 500, count: 10 }
];
const money = 600;
You should check count of banknot after "if" on 30 line too.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incorrect answer for