From 1e7ce107613c578fdb99d3480e2e04e351434ac6 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Mon, 17 Dec 2018 21:18:43 -0600 Subject: 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.--- .../sources/CoinChangeDynamicProgramming.java | 29 ++++++++++++++++++++++ .../tests/CoinChangeDynamicProgrammingTest.java | 13 ++++++++++ 2 files changed, 42 insertions(+) create mode 100644 AlgoDesignAndTechniqueEdxJava/sources/CoinChangeDynamicProgramming.java create mode 100644 AlgoDesignAndTechniqueEdxJava/tests/CoinChangeDynamicProgrammingTest.java 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)); + } + +} -- cgit v1.2.3