forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATM.java
More file actions
55 lines (43 loc) · 1.71 KB
/
Copy pathATM.java
File metadata and controls
55 lines (43 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package by.andd3dfx.common;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* Есть банкомат (ATM), который заряжают купюрами.
* Надо реализовать метод withdraw() для выдачи заданной суммы amount имеющимися в банкомате купюрами.
* Метод withdraw() - мутирующий, т.е. меняет состояние банкомата после вызова (кол-во купюр может уменьшиться).
* </pre>
*/
public class ATM {
private Map<Integer, Integer> state;
private List<Integer> nominals;
public ATM(Map<Integer, Integer> state) {
this.state = new HashMap<>(state);
this.nominals = state.keySet().stream()
.sorted(Comparator.reverseOrder()).toList();
}
public Map<Integer, Integer> withdraw(int amount) {
var result = new HashMap<Integer, Integer>();
for (var nominal : nominals) {
if (nominal > amount || state.get(nominal) == 0) {
continue;
}
int count = amount / nominal;
count = Math.min(count, state.get(nominal));
result.put(nominal, count);
amount -= nominal * count;
if (amount == 0) {
break;
}
}
if (amount > 0) {
throw new IllegalStateException("Could not perform withdraw!");
}
for (var nominal : result.keySet()) {
state.put(nominal, state.get(nominal) - result.get(nominal));
}
return result;
}
}