Hello i'm trying to create an algorythm that finds out how many ways i can get change back. But i just can't get the implemtation right, i keep getting 4 where i should get 6 and i just can't see why.
This is my implementation in C#, it is create from the pseudocode from http://www.algorithmist.com/index.php/Coin_Change
private static int[] S = { 1, 2, 5 };
private static void Main(string[] args)
{
int amount = 7;
int ways = count2(amount, S.Length);
Console.WriteLine("Ways to make change for " + amount + " kr: " + ways.ToString());
Console.ReadLine();
}
static int count2(int n, int m)
{
int[,] table = new int[n,m];
for (int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
// Rules
// 1: table[0,0] or table[0,x] = 1
// 2: talbe[i <= -1, x] = 0
// 3: table[x, j <= -1] = 0
int total = 0;
// first sub-problem
// count(n, m-1)
if (i == 0) // rule 1
total += 1;
else if (i <= -1) // rule 2
total += 0;
else if (j - 1 <= -1)
total += 0;
else
total += table[i, j-1];
// second sub-problem
// count(n-S[m], m)
if (j - 1 <= -1) // rule 3
total += 0;
else if (i - S[j - 1] == 0) // rule 1
total += 1;
else if (i - S[j - 1] <= -1) // rule 2
total += 0;
else
total += table[i - S[j-1], j];
table[i, j] = total;
}
}
return table[n-1, m-1];
}