Last active
August 17, 2016 11:23
-
-
Save BeachBird/9fddce3dd9a3c5b5a716 to your computer and use it in GitHub Desktop.
Functional Programming Principles in Scala. Recfun. Exercise 1: Pascal’s Triangle Exercise 2: Parentheses Balancing Exercise 3: Counting Change
This file contains 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,r) => 1 | |
case (c,r) if (c==r) => 1 | |
case (c,r) => pascal(c,r-1) + pascal(c-1,r-1) | |
} | |
//println(pascal(1,10)) | |
/** | |
* Exercise 2 | |
*/ | |
def balance(chars: List[Char]): Boolean = { | |
def bal(chars: List[Char],c:List[Char]):Boolean={ | |
if(chars.isEmpty && c.isEmpty) true | |
else if(chars.isEmpty && !(c.isEmpty)) false | |
else { | |
chars.head match { | |
case '(' => bal(chars.tail,'('::c) | |
case ')' if(c.isEmpty) => false | |
case ')' if(c.head=='(') => bal(chars.tail,c.tail) | |
case _ => bal(chars.tail,c) | |
} | |
} | |
} | |
bal(chars,List()) | |
} | |
/** | |
* Exercise 3 | |
*/ | |
def countChange(money: Int, coins: List[Int]): Int = { | |
if(money==0) 0 else | |
coins match { | |
case Nil if(money>0) => 0 | |
case m :: ms if(money>m) => countChange(money-m, coins) + countChange(money,ms) | |
case m :: ms if(money==m) => 1 + countChange(money,ms) | |
case m :: ms if(money<m) => countChange(money, ms) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi,
can you please share the
recfun.zip
?it's unavailable from the page right now :(
(the one original zip file that you downloaded from server)