In: Computer Science
Problem 4: Coins
Used java please
You are given a target value in cents and some coins: quarters, dimes, nickels, and pennies (in that order). Your program should tell which coins add up to that target.
input:
63 3 2 5 3
output:
63 cents = 2 quarters, 1 dimes, 0 nickels, 3 pennies
Hints:
Your recursive function can have ten int parameters: targetValue, valueSoFar, quartersLeft, dimesLeft, nickelsLeft, penniesLeft, quartersSpent, dimesSpent, nickelsSpent, penniesSpent.
Base cases:
1. you hit the target value. print how many of each coin type you used and return
2. you're over the target value. return.
Recursive cases
Handle the four coin types in order: quarters, dimes, nickels, pennies
If you have quarters, and a quarter won't put you over the top, call the recursive function, adjusting valueSoFar, quartersLeft, and quartersSpent appropriately
Do the same for the other coin types
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You.
FindNumberOfChangeRecurse.java
package c8;
public class FindNumberOfChangeRecurse {
void calcualteChange(int targetValue,int
valueSoFar,int quartersLeft,int dimesLeft,int nickelsLeft,int
penniesLeft,int quartersSpent,int dimesSpent,int nickelsSpent,int
penniesSpent) {
if(valueSoFar==targetValue) {
System.out.printf("%d cents = %d quarters, %d dimes, %d nickels, %d
pennies",
targetValue,quartersSpent,dimesSpent,nickelsSpent,penniesSpent);
}else if(valueSoFar<targetValue)
{
int required =
targetValue - valueSoFar;
/*
System.out.println("Required is : "+required); */
if(quartersLeft>0 && required>=25) {
valueSoFar += 25;
quartersSpent++;
quartersLeft--;
}else
if(dimesLeft>0 && required>=10) {
valueSoFar += 10;
dimesSpent++;
dimesLeft--;
}else
if(nickelsLeft>0 && required>=5) {
valueSoFar += 5;
nickelsSpent++;
nickelsLeft--;
}else
if(penniesLeft>0 && required>=1) {
valueSoFar += 1;
penniesSpent++;
penniesLeft--;
}else {
System.out.printf("Error!!! There is not enough
coins for exact change of %d!!!",targetValue);
return ;
}
calcualteChange(
targetValue, valueSoFar, quartersLeft, dimesLeft, nickelsLeft,
penniesLeft, quartersSpent, dimesSpent, nickelsSpent,
penniesSpent);
}
}
private void calcualteChange(int i, int j, int k, int
l, int m) {
calcualteChange(i,0, j, k, l,
m,0,0,0,0);
}
public static void main(String[] args) {
FindNumberOfChangeRecurse
changeFinder = new FindNumberOfChangeRecurse();
changeFinder.calcualteChange(63, 3,
2, 5, 3);
}
}
outputs