Im stuck at this problem about the change of a vending machine (using 10ct, 20 ct, 50ct, 100ct and 200ct-coins.)
So lets say coffee costs 40cts. The user throws in 2€ (labeled 200cts).
Now im supposed to figure out how the change of 160cts is given back to the user. There are 2 conditions: A) Taking the shortest combination, but B) only if the register has enough coins to hand out said combination .
So in my example, the shortest combination is 100cts + 50cts + 10cts. But if, lets say, there are no 10ct coins left in the register, the prefered combination should be 100ct + 20ct + 20ct + 20ct.
public void coinChange (int change) {
int TwoEuroCount = 0, OneEuroCount= 0, FiftyCentsCount = 0, TwentyCentsCount = 0, TenCentsCount = 0;
while (change > 0) {
TwoEuroCount = change / 200;
if(register.availableTwoEuros(TwoEuroCount) == true) {
register.withdrawTwoEuros(TwoEuroCount);
change = change - 200 * TwoEuroCount;
//the method .availableTwoEuros returns true if AmountOfTwoEuros - TwoEuroCount >= 0
}
OneEuroCount = change / 100;
if(register.availableOneEuro(OneEuroCount) == true) {
register.withdrawOneEuro(OneEuroCount);
change = change - 100 * OneEuroCount;
}
FiftyCentsCount = change / 50;
if(register.availableFiftyCents(FiftyCentsCount) == true) {
register.withdrawFiftyCents(FiftyCentsCount);
change = change - 50 * FiftyCentsCount;
}
TwentyCentsCount = change / 20;
if (register.availableTwentyCents(TwentyCentsCount) == true) {
register.withdrawTwentyCents(TwentyCentsCount);
change = change - 20 * TwentyCentsCount;
}
TenCentsCount = change / 10;
if(register.availableTenCents(TenCentsCount) == true) {
register.withdrawTenCents(TenCentsCount);
change = change - 10 * TenCentsCount;
}
}
}
This works perfectly for finding the shortest combination if there are enough coins. But if i start with AmountTenCents = 0, the method will just take 1 Euro and 50cts and leave it at that.