I need to create a program that computes change, using dynamic programming with caching. The program is to return an array with the coins adding up to the change.
I have consulted this page for pseudocode regarding dynamic programming, but the output is only the number of coins, and I am unsure whether the below line actually implements caching.
if ((values[j] <=a)&& (1+coins[a-values[j]]<coins[a]))
Below is all the working code which still needs modification.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/**
@param amt value of change
@param values[] array of coin values
@param n number of available coins (length of values array)
*/
float DynamicMakeChange(int amt,int values[],int n){
int coins[amt]; //array of number of coins needed up to amt
coins[0]=0;
int a; //the current change to compute
// put number of coins in coins array at index a
for (a=1;a<=amt;a++){
int array[a];
int counter=0;
coins[a]=(int)INFINITY;
int j;
//loops all values of coins
for (j=0;j<n;j++){
// if current coin value is smaller or equal than a (the current change value)
// and if the number of coins at the current amount-the currently looped value of a coin
// is less than the number of coins at the current amount.
if ((values[j] <=a)&& (1+coins[a-values[j]]<coins[a])){
//array[counter++]=values[j];
coins[a]=1+coins[a-values[j]];
}
}
}
return coins[amt];
}
int main()
{
int choice;
int array[] = { 1,2,5,10,20,50,100,200};
printf("Please enter change to turn to coins:\n");
scanf("%d",&choice);
int n= sizeof(array)/sizeof(array[0]);
float jasdkas=DynamicMakeChange(choice,array,n);
printf("Number of coins: %.0f",jasdkas);
return 0;
}
This, as stated in the link you provided should be solved using recursion . Your solution is not recursive. You´re program should recur, eg call itself. I am unsure what you needed to return but if it was the addition of the values in the int array then there should be something like:
inside DynamicMakeChange():
if (n>0)
return (array[n] + DynamicMakeChange(choice,array[n-1],n-1));
return 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.