I found a piece of code that I was writing for interview prep few months ago.
According to the comment I had, it was trying to solve this problem:
Given some dollar value in cents (e.g. 200 = 2 dollars, 1000 = 10 dollars), find all the combinations of coins that make up the dollar value. There are only pennies, nickels, dimes, and quarters allowed. (quarter = 25 cents, dime = 10 cents, nickel = 5 cents, penny = 1 cent)
For example, if 100 was given, the answer should be:
4 quarter(s) 0 dime(s) 0 nickel(s) 0 pennies
3 quarter(s) 1 dime(s) 0 nickel(s) 15 pennies
etc.
This can be solved in both iterative and recursive ways, I believe. My recursive solution is quite buggy, and I was wondering how other people would solve this problem. The difficult part of this problem was making it as efficient as possible.
In Scala Programming language i would do it like this:
I would favor a recursive solution. You have some list of denominations, if the smallest one can evenly divide any remaining currency amount, this should work fine.
Basically, you move from largest to smallest denominations.
Recursively,
Here's my python version of your stated problem, for 200 cents. I get 1463 ways. This version prints all the combinations and the final count total.
This blog entry of mine solves this knapsack like problem for the figures from an XKCD comic. A simple change to the
items
dict and theexactcost
value will yield all solutions for your problem too.If the problem were to find the change that used the least cost, then a naive greedy algorithm that used as much of the highest value coin might well fail for some combinations of coins and target amount. For example if there are coins with values 1, 3, and 4; and the target amount is 6 then the greedy algorithm might suggest three coins of value 4, 1, and 1 when it is easy to see that you could use two coins each of value 3.
Here's some absolutely straightforward C++ code to solve the problem which did ask for all the combinations to be shown.
But I'm quite intrigued about the sub problem of just calculating the number of combinations. I suspect there's a closed-form equation for it.
Clean scala function:
Below is python solution: