Skip to content

Instantly share code, notes, and snippets.

@belushkin
Created April 22, 2015 19:33
Show Gist options
  • Save belushkin/117d3d78b846d2754da7 to your computer and use it in GitHub Desktop.
Save belushkin/117d3d78b846d2754da7 to your computer and use it in GitHub Desktop.
Recursion scala exercises
package recfun
import common._
object Main {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
println("Parentheses Balancing")
println(balance(":-)".toList))
println("Counting Change")
println(countChange(4, List(1,2,3)))
}
/**
* Exercise 1
*/
def pascal(c: Int, r: Int): Int = {
if (c == 0 || c == r) 1
else pascal(c - 1, r - 1) + pascal(c, r - 1)
}
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = {
def loop(chars: List[Char], acc: Int): Boolean =
if (chars.isEmpty) {
acc == 0
} else {
val h = chars.head
val n =
if (h == '(') acc + 1
else if (h == ')') acc - 1
else acc
if (n >= 0) loop(chars.tail, n)
else false
}
loop(chars, 0)
}
/**
* Exercise 3
*/
def countChange(n: Int, coins: List[Int]): Int = {
def f(coins: List[Int], m: Int, n: Int): Int =
if (n == 0) 1
else if (n < 0) 0
else if (m <= 0 && n >= 1) 0
else f(coins, m - 1, n) + f(coins, m, n-coins(m-1))
f(coins, coins.length, n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment