Last active
April 23, 2017 15:09
-
-
Save ph87/acfb2ec0c8dbd0ca2745edd4bec03707 to your computer and use it in GitHub Desktop.
Functional Programming in Scala, Course 1, Exercises
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 | |
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("Parentheses Balancing") | |
val lista = ( | |
"(if (zero? x) max (/ 1 x))", | |
"I told him (that it’s not (yet) done). (But he wasn’t listening)", | |
":-)", | |
"())(" | |
) | |
lista.productIterator.foreach(arg => {print(arg);print(balance((arg+"").toList));println()}) | |
println("Counting Change") | |
println(countChange(4, List(1, 2))) | |
} | |
/** | |
* Exercise 1 | |
*/ | |
def pascal(c: Int, r: Int): Int = { | |
if (c == 0 || r ==c) { | |
1; | |
} else { | |
pascal(c, r-1) + pascal(c-1, r-1); | |
} | |
} | |
/** | |
* Exercise 2 | |
*/ | |
def balance(chars: List[Char]): Boolean = { | |
def balIter(cs: List[Char], c: Int):Boolean = { | |
if (cs.isEmpty) { | |
if (c == 0) true else false | |
} else { | |
cs.head.toString match { | |
case ")" => if (c < 1) false else balIter(cs.tail, c - 1); | |
case "(" => balIter(cs.tail, c + 1); | |
case _ => balIter(cs.tail, c); | |
} | |
/** | |
* if (cs.head.toString == ")") { | |
* if (c < 1) false else balIter(cs.tail, c - 1); | |
* } else if (cs.head.toString == "(") { | |
* balIter(cs.tail, c + 1); | |
* } else { | |
* balIter(cs.tail, c); | |
* } | |
*/ | |
} | |
} | |
balIter(chars, 0) | |
} | |
/** | |
* Exercise 3 | |
*/ | |
def countChange(money: Int, coins: List[Int]): Int = { | |
if (money == 0) 1 else if (money <= 0 || coins.isEmpty) 0 else {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