I’m trying to write a function that explores all possible combinations of numbers , given as an array , in hopes to find the minimal group of numbers that add up to a certain amount , which is passed as an argument.
Here’s what I’ve been doing , which seems to be working for some but not all cases;
I choose a number, subtract it from the total sum , and pass the new sum to the function,with the limits of the array intact , which gives me the option to re-choose the number,
in the second call I pass the new sum,i.e, total sum minus current chosen number , but I downsize the array by one, which mean that I won’t be choosing the same number again.
However , I’ve realized that I’m not covering all the choices, because in any case I’m assuming that any number is vital for the solution , but I don’t know which arguments to pass in order to cover the third option , which is not choosing the number,meaning i’ts not subtracted from the sum , and downsizing the array.
You’re help would be greatly appreciated , and btw , I’m writing in C.
int howManyCoins(int*coins,int size,int sum)
{
return howManyCoins_aux(coins,size,sum,size-1);
}
int howManyCoins_aux(int*coins,int size, int sum,int chosen)
{
if (sum==0)return 1;
if (sum<0)return 0;
if (chosen==0) return 0;
if (coins[chosen]>sum) return 0;
int res1=0,res2=0,best_solution=0;
for (int i=chosen;i>=0;i--)
{
res1+=howManyCoins_aux(coins,size,sum-coins[i],chosen);
res2+=howManyCoins_aux(coins,size,sum-coins[i],chosen-1);
if(!(res1+res2)) best_solution=0;
else if (res1==0) best_solution=res2;
else if (res2==0) best_solution=res1;
else best_solution=res2>res1?res1:res2;
}
return best_solution;
}
You can simplify your choices to: Choosing the coin and being able to re-choose the coin or not choosing the coin (recursion will cover all option)
Replace:
with
If you can only pick 1 of each coin: (which is the change-making problem)
Your algorithm is somewhat unclear, and I think there’s a lot of repetition. You can get rid of the for loop, and change your function to something like: (untested)
That being said, recursion probably isn’t the way to go (it will take very long, even on small datasets). Sounds like integer programming. There are a few options for solving it in the link.