This question usually comes out a lot in job-interviews. The common method of implementation is using a recursive function. Save the following function in payBill.m
function payBill(billList,billCount,Amount)
billList=sort(billList,'descend');
maxN=floor(Amount/billList(1));
if (numel(billList)==1)
reminder=mod(Amount,billList);
if (reminder==0)
count=[billCount maxN];
disp(count)
end
elseif (numel(billList)>1)
for i=maxN:-1:0
reminder=Amount-i*billList(1);
payBill(billList(2:end),[billCount i],reminder);
end
end
end
Now let's say you want to see all the combination of paying 7 cents using 1cent, 2cent, and 5cent coins. You can type the following command
It will generate all the combination possible as follow:
1 1 0
1 0 2
0 3 1
0 2 3
0 1 5
0 0 7
Note 1: when calling the function the order of billList doesn't matter. We could have put in [1 2 5] or [2 5 1] or [1 5 2], doesn't matter.
Note 2: when the counts are printed, regardless of the order you put the billList it would be always from the highest value coin to the lowest. Note in our example we gave [1 5 2] but the first number in the output is the count of 5 cents coin.
Note 3: if there is no possible combination to pay the exact amount nothing is printed. try payBill([3 5],[],7). There is no combination of 3cents coin and 5 cents coin to pay 7 cents. so nothing would be printed.
to get your example type, i.e. paying 32 cents using 2cents, 3cents, and 4cents coin type:
the following output is generated. Note that the first column is for the highest value coin, i.e. 4cents and then the next column is for 3 cents and the last column is for 2cents.
8 0 0
7 0 2
6 2 1
6 0 4
5 4 0
5 2 3
5 0 6
4 4 2
4 2 5
4 0 8
3 6 1
3 4 4
3 2 7
3 0 10
2 8 0
2 6 3
2 4 6
2 2 9
2 0 12
1 8 2
1 6 5
1 4 8
1 2 11
1 0 14
0 10 1
0 8 4
0 6 7
0 4 10
0 2 13
0 0 16
Best Answer