I'm having some trouble coming up with a working algorithm for the following problem.
Given determined quantities of available coins from 100, 50, 25 and 10 cents, I need to find how to fit a combination of these coins into a given value x. (it doesn't have to be optimal, any combination from availables coins will do).
So far, I've got this code, which works only for some cases.
struct coins{
int valor;
int quant;
};
int change = 0;
int changecoins[4] = {0};
struct coins available_coins[4] = { 0 };
moedas_disp[3].value = 10; //10 cents coins
moedas_disp[2].value = 25; //25 cents coins
moedas_disp[1].value = 50; //50 cents coins
moedas_disp[0].value = 100; //100 cents coins
//quantity values just for test purposes
moedas_disp[3].quant = 10; //10 cents coins
moedas_disp[2].quant = 15; //25 cents coins
moedas_disp[1].quant = 8; //50 cents coins
moedas_disp[0].quant = 12; //100 cents coins
for(int i=0; i<4; i++){
while((change/available_coins[i].value>0)&&(available_coins[i].quant>0)){
change -= available_coins[i].value;
available_coins[i].quant--;
changecoins[i]++;
}
}
if(change>0){
printf("It was not possible to change the value");
}
else{
printf("Change:\n");
printf("\t%d 100 cent coin(s).\n", changecoins[0]);
printf("\t%d 50 cent coin(s).\n", changecoins[1]);
printf("\t%d 25 cent coin(s).\n", changecoins[2]);
printf("\t%d 10 cent coin(s).\n", changecoins[3]);
}
However for quantities like 30 this won't work. The program will fit 1 coin of 25 cents, but then have 5 cents left, which will fail to compute. This also occurs with 40, 65, and so on.
Thanks in advance!