i was surfing the internet when i came across this algorithm(making change) and implemented it as below...but still is there any efficient way to do this...also how can i find the complexity for the same from program i implemented...
1>algorithm is as follows
makechange(c[],n) //c will contain the coins which we can take as our soln choice and 'n' is the amount we want change for
soln<-NULL//set that will hold solution
sum=0
while(sum!=n)
{
x<-largest item in c such that sum+x<=n
if(there is no such item)
return not found
soln <- soln U {a coin of value x}
sum=sum+x
return soln
}
2>here is what i have tried
#include<stdio.h>
#include<conio.h>
void main() {
int c[]= {100,50,20,10,5,1},soln[6];
int num,i,j,sum=0,x,k,flag=0;
clrscr();
printf("\nEnter amount to make change:");
scanf("%d",&num);
for(i=0;i<6;i++) {
soln[i]=NULL;
}
j=0;
while(sum!=num) {
for(i=0;i<6;i++) {
if(sum+c[i]<=num) {
x=c[i];
break;
}
}
sum=sum+x;
for(k=0;k<6;k++) {
if(soln[k]==x) {
flag=1;
}
}
if(flag!=1)
soln[j]=x;
j++;
}
printf("\nsoln contains coins below:");
j=0;
while(soln[j]!=NULL) {
printf("%d ",soln[j]);
j++;
}
getch();
}
any help would be appreciated...thank you...
For fun, here's a
constexpr
version!Demo: Live On Coliru
Output:
Version without boost: http://liveworkspace.org/code/3uU2AS$0
The other approach is to go through the coin options, staring with the largest, and taking as many of those as you can without going negative, and then on to the next largest, and so on:
Obviously (I hope) this require that
c
stores the coin values from largest to smallest and requires a check onresult_exact
to know if the change is exactly correct.