Reputation: 61
I'm trying to solve this problem where I need to simulate a sort of atm cash out. The program will ask 3 types of dollar bills and store it in 3 different bays e.g. bay 1 = 20; bay 2 = 50; bay 3 = 100; After the program asks for the cash out amount and give a maximum of 3 options if it is avaiable.
For example: cash out amount: U$ 220
A) 2 x U$ 100 + 1 x U$ 20
B) 1 x U$ 100 + 2 x U$ 50 + 1 x U$ 20
C) 4 x U$ 50 + 1 x U$ 20
Im struggling in finding a way to solve the B & C options, i don't know if im tunnel visioning in the way that i 'solved' the A option because i feel like there must be a much simpler way of calculating it
a,b & c variables are a bubble sort of the bay values
if(cash_out >= a){
left = total % a; //total = cash_out;
if(left == 0){
cont_A = total / a;
} else {
cont_A = total / a;
total = left;
if(total >= b){
left = total % b;
cont_B = total / b;
total = left;
if(total != 0){
cont_C = total / c;
}
} else {
cont_C = total / c;
}
}
} else if(cash_out >= b){
left = total % b;
if(left == 0){
cont_B = total / b;
left = total % b;
if(left == 0){
cont_C = total / c;
}
} else {
cont_B = total / b;
total = left;
if(total >= c){
cont_C = total / c;
}
}
} else {
cont_C = total / c;
}
Just to be clear i'm not asking so someone will solve the whole thing for me, I just want to understand how I should be approaching the problem
The code is what i did for the A option
Upvotes: 0
Views: 194
Reputation: 44339
As your problem involves fairly small numbers, you could start with a brute force method, i.e. simply trying all combinations in the possible range.
Like
#include <stdio.h>
int main(void) {
int bay[3] = {100, 50, 20};
int cash_out = 220;
for (int x = cash_out/bay[0]; x >= 0; --x)
{
for (int y = cash_out/bay[1]; y >= 0; --y)
{
for (int z = cash_out/bay[2]; z >= 0; --z)
{
if (cash_out == (x * bay[0] + y*bay[1] + z*bay[2]))
{
printf("%d %d %d\n", x, y, z);
}
}
}
}
return 0;
}
This will print:
2 0 1
1 2 1
1 0 6
0 4 1
0 2 6
0 0 11
Of cause a brute force method like the above is not optimal. So your next steps are to optimize the code.
First step would be to get rid of the inner most for-loop as it is completely unnecessary. I'll leave that as an exercise for you (tip: z
can be calculated directly).
Second step would be to limit the range of the second for-loop by taking into account the amount "used" by the first loop. Again, I'll leave that as an exercise for you.
Upvotes: 2