Skip to content

Instantly share code, notes, and snippets.

@aSipiere
Created February 4, 2018 22:52
Show Gist options
  • Save aSipiere/298919f6e4e49b929e50f850ef9c4503 to your computer and use it in GitHub Desktop.
Save aSipiere/298919f6e4e49b929e50f850ef9c4503 to your computer and use it in GitHub Desktop.
recursive functions
package recfun
import scala.collection.mutable.ListBuffer
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()
}
}
/**
* 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 f(chars: List[Char], num: Int): Boolean = {
(chars,num) match {
case (Nil,num) => return num == 0
case (c :: tail,num) =>
if(num < 0) return false
if(c == '(') return f(tail,num+1)
if(c == ')') return f(tail,num-1)
else return f(tail,num)
}
}
f(chars,0)
}
/**
* Exercise 3
*/
def countChange(money: Int, coins: List[Int]): Int = {
def count(m: Int, c: List[Int]) : Int = {
if (c.isEmpty) 0
else if (m - c.head == 0) 1
else if (m - c.head < 0) 0
else countChange(m - c.head, c) + countChange(m, c.tail)
}
count(money, coins.sorted)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment