Last active
March 17, 2022 16:36
-
-
Save jianwu-github/b236f504a802f9644bd9 to your computer and use it in GitHub Desktop.
Solve "Counting Change" Problem with Scala
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
/** | |
* Counting Change Problem: | |
* How many different ways can we make change of $ 1.00, given half-dollars, quarters, dimes, | |
* nickels, and pennies? More generally, counts how many different ways you can make change | |
* for an amount, given a list of coin denominations. For example, there are 3 ways to give | |
* change for 4 if you have coins with denomiations 1 and 2: 1+1+1+1, 1+1+2, 2+2. | |
* | |
* A standard algorithm using recursion is described in <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2">Tree Recursion</a> | |
* from MIT Press Book "Structure and Interpretation of Computer Programs" as: | |
* We can divide the ways to make change into two groups: | |
* 1). those ways making change without using first coin | |
* 2). those ways making change that do use the first coin, those are equivalent to all the | |
* ways to make change for the amount (original amount - value of first coin) | |
*/ | |
object CountingChange { | |
def countChange(money: Int, coins: List[Int]): Int = { | |
def findCombinationsCount(money: Int, coins: List[Int], coinCheckIndex: Int): Int = | |
if (money == 0) 1 | |
else if (money < 0) 0 // coin is bigger than remaining amount of money | |
else if (coins.length == coinCheckIndex) 0 // all the coins are used | |
else { | |
val usingFirstCoin = findCombinationsCount(money - coins.apply(coinCheckIndex), coins, coinCheckIndex) | |
val usingRestCoins = findCombinationsCount(money, coins, coinCheckIndex + 1) | |
usingFirstCoin + usingRestCoins | |
} | |
findCombinationsCount(money, coins, 0) | |
} | |
def main(args: Array[String]) { | |
val coinList : List[Int] = List(1, 5, 10) | |
println("countingChange(12) is " + countChange(12, coinList)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment