Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to determine coin combinations

I was recently faced with a prompt for a programming algorithm that I had no idea what to do for. I've never really written an algorithm before, so I'm kind of a newb at this.

The problem said to write a program to determine all of the possible coin combinations for a cashier to give back as change based on coin values and number of coins. For example, there could be a currency with 4 coins: a 2 cent, 6 cent, 10 cent and 15 cent coins. How many combinations of this that equal 50 cents are there?

The language I'm using is C++, although that doesn't really matter too much.

edit: This is a more specific programming question, but how would I analyze a string in C++ to get the coin values? They were given in a text document like

4 2 6 10 15 50 

(where the numbers in this case correspond to the example I gave)

like image 762
ahota Avatar asked May 05 '11 11:05

ahota


People also ask

How do you calculate possible combinations for a coin problem?

Given denominations of 'N' coins and an amount, we need to calculate the maximum number of ways(or combinations) the given amount can be paid. We are also given an infinite supply of each coin. So, here the possible combinations are 2 + 2 + 3 = 7 (amount) and 2 + 5 = 7 (amount).

What is the cashier's algorithm?

Cashier's algorithm. At each iteration, add coin of the largest value that does not take us past the amount to be paid. Cashier's algorithm. At each iteration, add coin of the largest value that does not take us past the amount to be paid.

How many combinations of coins can make a dollar?

Larry King said in his USA Today column that there are 293 ways to make change for a dollar.

Is coin change a greedy algorithm?

The famous coin change problem is a classic example of using greedy algorithms. Let's understand what the problem is. According to the coin change problem, we are given a set of coins of various denominations. Consider the below array as the set of coins where each element is basically a denomination.


2 Answers

This problem is well known as coin change problem. Please check this and this for details. Also if you Google "coin change" or "dynamic programming coin change" then you will get many other useful resources.

like image 171
taskinoor Avatar answered Sep 18 '22 13:09

taskinoor


Here's a recursive solution in Java:

// Usage: int[] denoms = new int[] { 1, 2, 5, 10, 20, 50, 100, 200 };       
// System.out.println(ways(denoms, denoms.length, 200));
public static int ways(int denoms[], int index, int capacity) {
    if (capacity == 0) return 1;
    if (capacity < 0 || index <= 0 ) return 0;
    int withoutItem = ways(denoms, index - 1, capacity); 
    int withItem = ways(denoms, index, capacity - denoms[index - 1]); 
    return withoutItem + withItem;
}
like image 43
zc22 Avatar answered Sep 18 '22 13:09

zc22