package recfun
import scala.util.control.TailCalls._
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(countChange(14,List(5,4)))
}
/**
* Exercise 1
*/
def pascal(c: Int, r: Int): Int = {
def loop(acc:Int, n:Int, c: Int, r: Int ): Int = {
if (c == 0 || r == c) {
acc
} else {
loop(acc * r / n , n + 1, c - 1, r - 1)
}
}
loop(1, 1, c, r)
}
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = {
def loop(bra: Int, rem: List[Char]): Int = {
if (rem.isEmpty || bra < 0) {
bra
} else {
val new_bra = rem.head match {
case '(' => bra + 1
case ')' => bra - 1
case _ => bra
}
loop(new_bra, rem.tail)
}
}
loop(0, chars) == 0
}
/**
* Exercise 3
*/
def countChange(money: Int, coins: List[Int]): Int = {
if (money < 0) 0
else coins match {
case Nil => if (money == 0) 1 else 0
case x::xs => countChange(money - x, coins) + countChange(money, xs)
}
}
}