I have written a code to calculate the minimum number of coins using Greedy algorithm and Dynamic algorithm, but the Dynamic algorithm part doesn’t work properly. There is a Null value going to array, I can’t find it. Please HELP me. I need a answer as soon as possible.
#include <stdio.h>
int n;
int denom[]={1,2,4,5,20,25};
int coinCounter(int n);
int main(){
printf("Please Enter a Number : ");
scanf("%d",&n);
int coinmin,orin,i;
orin=n;
i=coinmin=0;
for(i=(sizeof(denom)/4)-1;i>=0;i--){
coinmin =coinmin+n/denom[i];
n=n%denom[i];
}
printf("Coin Min By Greedy Algorithm : %d\n",coinmin);
printf("Dynamic Algorithm : %d\n",coinCounter(orin));
return 0;
}
int coinCounter(int n){
int opt[n];
int largest[n];
int i,j,a;
i=j=0;
for(j=1;j<=n;j++){
opt[j]=10000;
//printf("xxn");
for(i=(sizeof(denom)/4)-1;i>=0;i--){
if(denom[i]==j){
opt[j]=1;
largest[j]=j;
}
else if(denom[i]<j){
a=opt[j-denom[i]]+1;
}
if(a<opt[j]){
opt[j]=a;
largest[j]=denom[i];
}
}
}
return opt[n];
}
I edited the Code as following, but the answer is not coming
int coinCounter(int n){
int opt[n];
int largest[n];
int i,j,a;
i=j=0;
for(j=1;j<n;j++){
opt[j]=10000;
printf("xxn");
for(i=(sizeof(denom)/4)-1;i>=0;i--){
if(denom[i]==j){
opt[j]=1;
largest[j]=j;
}
else if(denom[i]<j){
a=opt[j-denom[i]]+1;
}
if(a<opt[j]){
opt[j]=a;
largest[j]=denom[i];
}
}
}
return opt[n-1];
}
hey these are the results I’m Getting
Please Enter a Number : 8 Coin Min By Greedy Algorithm : 3 Dynamic Algorithm : 1
Another answer I’m getting I can’t figure out what I’m doing wrong
Please Enter a Number : 71 Coin Min By Greedy Algorithm : 4 Dynamic Algorithm : 3
change to
Edit:
Another bug with the algorithm
your variable “a” is not initialized and you are using it in if condition.
think of the case when
denom[i]>jyour variable “a” would not be initialized
so depending upon what garbage value it has , results will vary
bug is here , but it shows up when you change opt allocation, because that allocation changes the condition. What I want to say is –
if (X<Y), depends on both X and Y. Problem is with X, but because you change Y, the condition changes and you get different result