Last active
April 3, 2018 06:14
-
-
Save Zoha131/bb3140ff26557438bd55759658de76d2 to your computer and use it in GitHub Desktop.
Algorithm Lab Mid Exam Solution || Section D || Spring-2018 || Daffodil International University
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
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
Dear Joha,
Good job ! The solution is absolutely correct for the sample inputs of lab mid exam. But the way you have done it its not might give the best answer always as it is done using Greedy Approach. So you should replace the word Dynamic by Greedy in comment section of your code. Happy coding :)