Created
April 3, 2013 00:49
-
-
Save chancila/5297569 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = (c,r) match { | |
case (0,0) => 1 | |
case (0,_) => 1 | |
case (a,b) if a == b => 1 | |
case (a,b) => pascal(a-1,b-1) + pascal(a,b-1) | |
} | |
/** | |
* Exercise 2 | |
*/ | |
def balance(chars: List[Char]): Boolean = balance_inner(chars,false,0); | |
def balance_inner(chars: List[Char],isOpen : Boolean,depth : Int) : Boolean = chars match { | |
case head :: tail => { | |
head match { | |
case '(' => balance_inner(tail,true,depth+1) | |
case ')' => balance_inner(tail,(depth-1) != 0,depth-1) | |
case _ => balance_inner(tail,isOpen,depth) | |
} | |
} | |
case Nil => { | |
!isOpen && depth == 0 | |
} | |
} | |
/** | |
* Exercise 3 | |
*/ | |
def countChange(money: Int, coins: List[Int]): Int = { | |
(money,coins) match { | |
case (0,Nil) => 1 | |
case (a,_) if a < 0 => 0 | |
case (_,Nil) => 0 | |
case (_,head :: tail) => { | |
countChange(money - head,coins) + countChange(money,tail) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment