Make change for a dollar amount
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
I need to write a function that generates all of the ways that change for a an amount can be made. However, we are not using nickle, dimes, and quarters to make this change. We are using a set of inputted values.
For example, if my inputs are: X = [2 3 4] and Y = 32
My output should be:
16 0 0
14 0 1
10 0 3
etc...,
showing all of the ways that I can make a sum of 32 with the coin values 2,3, and 4.
I've tried to use some sort of permutation to do this, and I've also tried using mod(x,y) in different fashions, and cannot seem to get the correct result.
Any insights? Thanks a lot folks!
채택된 답변
Mohammad Abouali
2014년 12월 6일
편집: Mohammad Abouali
2014년 12월 6일
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
payBill([1 5 2],[],7)
It will generate all the combination possible as follow:
1 1 0 % 1x 5 cents + 1x 2 cents
1 0 2 % 1x 5 cents + 2x 1 cents
0 3 1 % 3x 2 cents + 1x 1 cents
0 2 3 % 2x 2 cents + 3x 1 cents
0 1 5 % 1x 2 cents + 5x 1 cents
0 0 7 % 7x 1 cents
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:
payBill([2,3,4],[],32)
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 % 8x 4 cents
7 0 2 % 7x 4 cents + 2x 2 cents
6 2 1 % and so on
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
댓글 수: 7
Scott
2014년 12월 6일
That appears to do exactly what I need! thank you so much.
But if i only want the function to take two inputs, namely:
1) the denominations of the change that can be made i.e. [1 3 5] 2) the total amount that I would like to make change for i.e. 30
Mohammad Abouali
2014년 12월 6일
편집: Mohammad Abouali
2014년 12월 6일
So I changed the code in such a way that it does not require that third parameter at all any more. so only two parameters (those that you want)
Here is the new code:
function count=payBill(billList,Amount)
billList=sort(billList,'descend');
maxN=floor(Amount/billList(1));
if (numel(billList)==1)
reminder=mod(Amount,billList);
if (reminder==0)
count=[billList;maxN];
else
count=[];
end
return;
elseif (numel(billList)>1)
count=reshape(billList,1,[]);
for i=maxN:-1:0
reminder=Amount-i*billList(1);
tmpCount=payBill(billList(2:end),reminder);
count=[count; ...
ones(size(tmpCount,1)-1,1)*i tmpCount(2:end,:)];
end
end
end
Note that the method to call the function has changed now. It actually returns all the combination and the first row is the ordered bill list (denominations). Here is an example:
count=payBill([1,2,5],5)
count =
5 2 1 % Note the first row is the denominations
% to guid each column coincide with which coin
1 0 0
0 2 1
0 1 3
0 0 5
If this is what you want, please accept the answer.
Scott
2014년 12월 6일
Mohammad Abouali
2014년 12월 6일
편집: Mohammad Abouali
2014년 12월 6일
count=payBill([2:4],32)
countCell=mat2cell(count,ones(size(count,1),1),size(count,2))
So countCell is gonna be cell array. each element is one triplet of count or generally one row of count. You can retrieve them later as follow
>> countCell{1} % note the first one is the denominations though.
ans =
4 3 2
>> countCell{2}
ans =
8 0 0
Scott
2014년 12월 6일
and actually it is assumed that our change denominations will be given in an ascending order. so that will change the code right?
Mohammad Abouali
2014년 12월 6일
편집: Mohammad Abouali
2014년 12월 6일
Nope. Doesn't need to change anything in the code. The code already takes care of that
If you look at note1 in my first reply as I said, doesn't matter how the denominations are inputed. It can be ascending, descending or even random order.
The output would be always in the descending order (highest denomination to the lowest)
If you want the output to be also in ascending order just flip the results using fliplr() , as follow:
count=fliplr( payBill([2:4],32) );
Mohammad Abouali
2014년 12월 6일
If your question is answered, please accept the answer.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
