-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathCoins.java
More file actions
40 lines (32 loc) · 987 Bytes
/
Copy pathCoins.java
File metadata and controls
40 lines (32 loc) · 987 Bytes
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
package vendingmachine.coin;
import java.util.EnumMap;
import java.util.Map;
public class Coins {
private final Map<Coin, Integer> coins;
public Coins(Map<Coin, Integer> coins){
this.coins = coins;
}
public int getCounts(Coin coin){
return coins.get(coin);
}
public Map<Coin, Integer> giveChange(int changeMoney){
Map<Coin, Integer> changes = new EnumMap<>(Coin.class);
for(Coin coin: Coin.values()){
if(coin.getAmount() > changeMoney){
changes.remove(coin);
continue;
}
int count = getCount(changeMoney, coin);
changes.put(coin, count);
changeMoney -= coin.getAmount() * count;
}
return changes;
}
private int getCount(int changeMoney, Coin coin) {
int count = coins.get(coin);
while(count * coin.getAmount() > changeMoney){
count--;
}
return count;
}
}