Just a few interesting pieces of Scala code
-
-
Save tongtie/9c72f261aa139fc09b58c6ca24db6a50 to your computer and use it in GitHub Desktop.
Counting change recursive algorithm in Scala
This file contains 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
/* | |
Write a recursive function that 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 denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2. | |
*/ | |
def countChange(money: Int, coins: List[Int]): Int = { | |
def loop(money: Int, coins: List[Int]): Int = { | |
if (money < 0 || coins.isEmpty ) 0 | |
else if (money == 0 ) 1 | |
else loop(money, coins.tail) + loop(money - coins.head, coins) | |
} | |
loop(money, coins) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment