Skip to content

Instantly share code, notes, and snippets.

@tongtie
Forked from jasonicarter/README.md
Last active May 6, 2018 03:18
Show Gist options
  • Save tongtie/9c72f261aa139fc09b58c6ca24db6a50 to your computer and use it in GitHub Desktop.
Save tongtie/9c72f261aa139fc09b58c6ca24db6a50 to your computer and use it in GitHub Desktop.
Counting change recursive algorithm in Scala

Scala

Just a few interesting pieces of Scala code

/*
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