Created
September 28, 2012 21:29
-
-
Save 4lex1v/3802174 to your computer and use it in GitHub Desktop.
Scala - week 1
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 = { | |
if (r < c) 0 | |
else if (c < 0) 0 | |
else if (r == 0) 1 | |
else pascal(c-1, r-1) + pascal(c, r-1) | |
} | |
/** | |
* Exercise 2 | |
*/ | |
def balance(chars: List[Char]): Boolean = { | |
val open: Char = '(' | |
val close: Char = ')' | |
def isOpen(ch: Char): Boolean = (ch == open) | |
def isClose(ch: Char): Boolean = (ch == close) | |
def isMatch(openChar: Char, closeChar: Char): Boolean = (isOpen(openChar) && isClose(closeChar)) | |
def isBalanced(inp: List[Char], stack: String): Boolean = | |
if (inp.isEmpty) stack.isEmpty | |
else if (isOpen(inp.head)) isBalanced(inp.tail, stack + inp.head) | |
else if (isClose(inp.head)) | |
(!stack.isEmpty && | |
isMatch(stack.charAt(0), inp.head) && | |
isBalanced(inp.tail, stack.substring(1))) | |
else isBalanced(inp.tail, stack) | |
isBalanced(chars, "") | |
} | |
/** | |
* Exercise 3 | |
*/ | |
def countChange(money: Int, coins: List[Int]): Int = { | |
def cc(amount: Int, kindsOfCoins: Int): Int = { | |
if (amount == 0) 1 | |
else if ((amount < 0) || (kindsOfCoins == 0)) 0 | |
else { | |
cc(amount, kindsOfCoins - 1) + | |
cc(amount - coins(kindsOfCoins-1), kindsOfCoins) | |
} | |
} | |
cc(money, coins.size) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment