Skip to content

Instantly share code, notes, and snippets.

@counter2015
Created July 30, 2019 08:50
Show Gist options
  • Save counter2015/c1aa5e73799c510a18e1093bd55eb35e to your computer and use it in GitHub Desktop.
Save counter2015/c1aa5e73799c510a18e1093bd55eb35e to your computer and use it in GitHub Desktop.
Functional Programming Principles in Scala Week1 Code
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()
}
}
/**
* Exercise 1
*/
def pascal(c: Int, r: Int): Int = {
if (c == 0 || c == r)
1
else
pascal(c-1, r-1) + pascal(c, r-1)
}
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = {
def balanced(chars: List[Char], count: Int): Boolean = {
if (chars.isEmpty) count == 0
else if (chars.head == '(') balanced(chars.tail, count + 1)
else if (chars.head == ')') count > 0 && balanced(chars.tail, count - 1)
else balanced(chars.tail, count)
}
balanced(chars, 0)
}
/**
* Exercise 3
*/
def countChange(money: Int, coins: List[Int]): Int = {
def count(money: Int, coins: List[Int]): Int = {
if (coins.isEmpty) 0
else if (money == coins.head) 1
else if (money < coins.head) 0
else count(money - coins.head, coins) + count(money, coins.tail)
}
count(money, coins.sorted)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment