Skip to content

Instantly share code, notes, and snippets.

@orend
Created September 23, 2012 01:31
Show Gist options
  • Save orend/3768467 to your computer and use it in GitHub Desktop.
Save orend/3768467 to your computer and use it in GitHub Desktop.
ex1 scala course
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()
}
}
/**
* Exercise 1
*/
def pascal(c: Int, r: Int): Int = {
if (r == 0 || c == 0 || r == c) 1 else
pascal(c, r-1) + pascal(c-1, r-1)
}
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = {
def inner_balance(count: Int, chars: List[Char]): Boolean = {
def charValue(c: Char): Int = {
c match {
case '(' => 1
case ')' => -1
case _ => 0
}
}
count match {
case c if c < 0 => false
case _ if chars.isEmpty => count == 0
case _ => inner_balance(count + charValue(chars.head), chars.tail)
}
}
inner_balance(0, chars)
}
/**
* Exercise 3
*/
def countChange(money: Int, coins: List[Int]): Int = {
money match {
case 0 => 1
case m if m < 0 => 0
case _ if coins.isEmpty => 0
case _ => countChange(money - coins.head, coins) + countChange(money, coins.tail)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment