Skip to content

Instantly share code, notes, and snippets.

@Zoha131
Last active April 3, 2018 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zoha131/bb3140ff26557438bd55759658de76d2 to your computer and use it in GitHub Desktop.
Save Zoha131/bb3140ff26557438bd55759658de76d2 to your computer and use it in GitHub Desktop.
Algorithm Lab Mid Exam Solution || Section D || Spring-2018 || Daffodil International University
import java.util.HashMap;
import java.util.Scanner;
/**
*
* @author Abir Hasan Zoha
*/
/**
*
* This is similar with greedy coin change problem
* The difference is that in this problem the input
* would be in decimal point.
*
* If somehow we can convert double to int then this
* would exactly same with dynamic coin change.
*/
public class CoinChange {
static int getCoingChange(double coins[], double amount){
int count = 0;
int coinsInt[] = new int[coins.length];
int amountInt = (int) (amount * 100);
// we converted the amount from double to int
// Do not forget to have bracket (amount * 100)
HashMap<Integer, Integer> needed = new HashMap<>();
for (int i = 0; i < coins.length; i++) {
coinsInt[i] = (int)(coins[i] *100);
//the the coin have been converted from double to int
//Be careful about the bracket in type casting
}
for (int i = 0; i < coins.length; i++) {
int temp = amountInt / coinsInt[i];
count += temp;
//increament the count variable with used coin
needed.put(coinsInt[i], temp);
//Stored used coin and number
amountInt = amountInt%coinsInt[i];
}
for (int i = 0; i < coins.length; i++) {
int temp = needed.get(coinsInt[i]);
if(temp > 0){
System.out.println("Coin "+ coins[i] + " needs "+temp+" times");
//Printed the used coin
}
}
return count;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.print("Please enter the ammount: ");
double amount= input.nextDouble();
System.out.print("Please enter the number of coins: ");
int n = input.nextInt();
double[] coins = new double[n];
System.out.println("Please enter the coin in Ascending: ");
for (int i = 0; i < n; i++) {
coins[i] = input.nextDouble();
}
System.out.print("\n\nTotal Coin: "+getCoingChange(coins, amount));
}
}
@Zoha131
Copy link
Author

Zoha131 commented Apr 3, 2018

Thank you sir, for pointing my mistake. I have changed the word.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment