Monday, September 16, 2013

Recursive program to find the number of ways a particular amount can be obtained using a given set of Currency values.


public class Coins {
private static int count = 0;
public static void main(String[] args) {
int[][] currencyList = {{5,10,20},{0,0,0}};
//The first row contains the list of the currency values available.
//The second row contains the frequency of each currency value.
//The number of columns in both the rows should be the same.
//Else an index-out-of-bounds exception will happen.
int sum=0;
int amount = 20;
int index=0;
computeCombinations(currencyList, sum, amount, index);
System.out.println("Total possible combinations: "+ Coins.count);
}

public static void computeCombinations(int[][] currencyList, int sum, int amount, int index) {
if(index >= currencyList[0].length) {
return;
}
else {
for(int i=0; i<=(amount/currencyList[0][index]);i++) {
currencyList[1][index]=i;
sum+=currencyList[0][index]*currencyList[1][index];
if(sum == amount) {
count++;
for(int j=0;j <=index; j++) {
if(currencyList[1][j] != 0) {
System.out.print(currencyList[0][j] + "-->" + currencyList[1][j] + " ");
}
}
System.out.println();
}
else {
computeCombinations(currencyList, sum, amount, index + 1);
sum-=currencyList[0][index]*currencyList[1][index];
}
}
}
}
}
Output:
20-->1
10-->2
5-->2 10-->1
5-->4
Total possible combinations: 4

No comments:

Post a Comment