summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHaidong Ji2018-12-17 21:18:43 -0600
committerHaidong Ji2018-12-17 21:18:43 -0600
commit1e7ce107613c578fdb99d3480e2e04e351434ac6 (patch)
tree9468a4bf0c26194392b9ae89e6b2574dce3e80c8
parent58dbf03988de550c68fad019bd34ab09a5ff0d07 (diff)
Coin change Dynamic Programming done!
Easy implementation of the algorithm described in course slide. It helped that I named variables according to the pseudo code. Getting array indexing right is always a bit tricky so pay attention.
-rw-r--r--AlgoDesignAndTechniqueEdxJava/sources/CoinChangeDynamicProgramming.java29
-rw-r--r--AlgoDesignAndTechniqueEdxJava/tests/CoinChangeDynamicProgrammingTest.java13
2 files changed, 42 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxJava/sources/CoinChangeDynamicProgramming.java b/AlgoDesignAndTechniqueEdxJava/sources/CoinChangeDynamicProgramming.java
new file mode 100644
index 0000000..4f3c2b9
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/sources/CoinChangeDynamicProgramming.java
@@ -0,0 +1,29 @@
+import java.util.Scanner;
+
+public class CoinChangeDynamicProgramming {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ int m = scanner.nextInt();
+ System.out.println(getChange(m));
+ }
+
+ public static int getChange(int money) {
+ // denominations: 1, 3, 4
+ int[] denominations = { 1, 3, 4 };
+ int[] minNumCoins = new int[money + 1];
+ for (int m = 1; m < minNumCoins.length; m++) {
+ minNumCoins[m] = Integer.MAX_VALUE;
+ for (int i = 0; i < denominations.length; i++) {
+ if (m >= denominations[i]) {
+ int numCoins = minNumCoins[m - denominations[i]] + 1;
+ if (numCoins < minNumCoins[m]) {
+ minNumCoins[m] = numCoins;
+ }
+ }
+ }
+ }
+ return minNumCoins[money];
+ }
+
+}
diff --git a/AlgoDesignAndTechniqueEdxJava/tests/CoinChangeDynamicProgrammingTest.java b/AlgoDesignAndTechniqueEdxJava/tests/CoinChangeDynamicProgrammingTest.java
new file mode 100644
index 0000000..602e013
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/tests/CoinChangeDynamicProgrammingTest.java
@@ -0,0 +1,13 @@
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class CoinChangeDynamicProgrammingTest {
+
+ @Test
+ void test() {
+ assertEquals(2, CoinChangeDynamicProgramming.getChange(2));
+ assertEquals(9, CoinChangeDynamicProgramming.getChange(34));
+ }
+
+}