|
| 1 | +package by.andd3dfx.common; |
| 2 | + |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/** |
| 9 | + * <pre> |
| 10 | + * Есть банкомат (ATM), который заряжают купюрами. |
| 11 | + * Надо реализовать метод withdraw() для выдачи заданной суммы amount имеющимися в банкомате купюрами. |
| 12 | + * Метод withdraw() - мутирующий, т.е. меняет состояние банкомата после вызова (кол-во купюр может уменьшиться). |
| 13 | + * </pre> |
| 14 | + * |
| 15 | + * @see <a href="https://youtu.be/LDKZtDevRRI">Video solution</a> |
| 16 | + */ |
| 17 | +public class ATM2 { |
| 18 | + |
| 19 | + private Map<Integer, Integer> state; |
| 20 | + private List<Integer> nominals; |
| 21 | + |
| 22 | + public ATM2(Map<Integer, Integer> state) { |
| 23 | + this.state = new HashMap<>(state); |
| 24 | + this.nominals = state.keySet().stream() |
| 25 | + .sorted(Comparator.reverseOrder()).toList(); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Withdraw asked amount using banknotes of ATM |
| 30 | + * |
| 31 | + * @param amount sum asked to withdraw |
| 32 | + * @return map with solution - pairs {banknote nominal->quantity} |
| 33 | + */ |
| 34 | + public Map<Integer, Integer> withdraw(int amount) { |
| 35 | + // Try to make withdraw using banknote of highest nominal, |
| 36 | + // in case of fail - try to start from next nominal |
| 37 | + for (int i = 0; i < nominals.size(); i++) { |
| 38 | + try { |
| 39 | + return withdraw(amount, i); |
| 40 | + } catch (IllegalStateException ex) { |
| 41 | + // do nothing |
| 42 | + } |
| 43 | + } |
| 44 | + throw new IllegalStateException("Could not perform withdraw!"); |
| 45 | + } |
| 46 | + |
| 47 | + private Map<Integer, Integer> withdraw(int amount, int nominalIndex) { |
| 48 | + if (nominalIndex >= nominals.size()) { |
| 49 | + throw new IllegalStateException("Could not perform withdraw!"); |
| 50 | + } |
| 51 | + |
| 52 | + var nominal = nominals.get(nominalIndex); |
| 53 | + if (nominal > amount || state.get(nominal) == 0) { |
| 54 | + return withdraw(amount, nominalIndex + 1); |
| 55 | + } |
| 56 | + |
| 57 | + var result = new HashMap<Integer, Integer>(); |
| 58 | + int count = amount / nominal; |
| 59 | + count = Math.min(count, state.get(nominal)); |
| 60 | + result.put(nominal, count); |
| 61 | + amount -= nominal * count; |
| 62 | + |
| 63 | + if (amount == 0) { |
| 64 | + mutateAtm(result); |
| 65 | + return result; |
| 66 | + } |
| 67 | + |
| 68 | + result.putAll(withdraw(amount, nominalIndex + 1)); |
| 69 | + return result; |
| 70 | + } |
| 71 | + |
| 72 | + private void mutateAtm(Map<Integer, Integer> result) { |
| 73 | + for (var nominal : result.keySet()) { |
| 74 | + state.put(nominal, state.get(nominal) - result.get(nominal)); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments