Senior
48
/** * Interfaccia per interagire con l'hardware del bancomat. */ interface Hardware { /** * Restituisce un array con il numero di banconote per denominazioni 50, 100, 500, 1000, 5000. * Il metodo funziona lentamente e genera rumore. * * @return array in cui ogni elemento corrisponde al numero di banconote di una denominazione specifica. * Ad esempio, [10, 20, 30, 40, 50] significa: * - 10 banconote da 50 rubli * - 20 banconote da 100 rubli * - 30 banconote da 500 rubli * - 40 banconote da 1000 rubli * - 50 banconote da 5000 rubli */ int[] getBillsCounts(); /** * Carica nella cassa le banconote indicate. * * @param billsCounts array con il numero di banconote per denominazioni [50, 100, 500, 1000, 5000]. * Ad esempio, [0, 1, 0, 2, 0] significa: * - 0 banconote da 50 rubli * - 1 banconota da 100 rubli * - 0 banconote da 500 rubli * - 2 banconote da 1000 rubli * - 0 banconote da 5000 rubli */ void giveBills(int[] billsCounts); } /** * Classe per implementare la logica del bancomat. * Qui si deve scrivere il codice */ class MyATM { /** * Hardware del bancomat. */ Hardware hardware; public boolean withdraw(int amount) { int[] counts = hardware.getBillsCounts(); int[] nom = {50, 100, 500, 1000, 5000}; int[] toGive = new int[5]; for (int i = 4; i >= 0; i--) { int needed = amount / nom[i]; int use = Math.min(needed, counts[i]); toGive[i] = use; amount -= use * nom[i]; } if (amount != 0) { return false; } hardware.giveBills(toGive); return true; } }
Le aziende dove è stato chiesto
Risposta dell'AI
sobes.tech AI
В представленном коде метод withdraw пытается выдать запрошенную сумму, используя купюры доступных номиналов, начиная с самых крупных. Однако такой жадный алгоритм не всегда находит решение, даже если оно существует.
Чтобы улучшить логику, можно реализовать динамическое программирование или перебор с возвратом (backtracking), чтобы найти комбинацию купюр, которая точно даст нужную сумму, учитывая ограничения по количеству купюр каждого номинала.
Пример улучшенного подхода с использованием рекурсии и мемоизации (псевдокод):
boolean tryWithdraw(int amount, int[] counts, int[] nom, int index, int[] toGive) {
if (amount == 0) return true;
if (index < 0 || amount < 0) return false;
for (int i = 0; i <= counts[index]; i++) {
toGive[index] = i;
if (tryWithdraw(amount - i * nom[index], counts, nom, index - 1, toGive)) {
return true;
}
}
toGive[index] = 0;
return false;
}
public boolean withdraw(int amount) {
int[] counts = hardware.getBillsCounts();
int[] nom = {50, 100, 500, 1000, 5000};
int[] toGive = new int[5];
if (!tryWithdraw(amount, counts, nom, nom.length - 1, toGive)) {
return false;
}
hardware.giveBills(toGive);
return true;
}
Такой подход гарантирует, что если сумма может быть выдана, то метод её найдет, несмотря на ограничения по количеству купюр.