Guest User

Untitled

a guest
Jun 21st, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. package recfun
  2.  
  3. object Main {
  4. def main(args: Array[String]) {
  5. println("Pascal's Triangle")
  6. for (row <- 0 to 10) {
  7. for (col <- 0 to row)
  8. print(pascal(col, row) + " ")
  9. println()
  10. }
  11. }
  12.  
  13. /**
  14. * Exercise 1
  15. */
  16. def pascal(c: Int, r: Int): Int = {
  17. if (c == 0 || r == c) 1
  18. else pascal(c - 1, r - 1) + pascal(c, r - 1)
  19. }
  20.  
  21. /**
  22. * Exercise 2
  23. */
  24. def balance(chars: List[Char]): Boolean = {
  25.  
  26. def isOpen(char: Char): Boolean =
  27. char == '('
  28.  
  29. def isClose(char: Char): Boolean =
  30. char == ')'
  31.  
  32. def balanceIter(_chars: List[Char], acc: Int): Boolean =
  33. if (_chars.isEmpty) acc == 0
  34. else if (acc < 0) false
  35. else if (isOpen(_chars.head)) balanceIter(_chars.tail, acc + 1)
  36. else if (isClose(_chars.head)) balanceIter(_chars.tail, acc - 1)
  37. else balanceIter(_chars.tail, acc)
  38.  
  39. balanceIter(chars, 0)
  40. }
  41.  
  42. /**
  43. * Exercise 3
  44. */
  45. def countChange(money: Int, coins: List[Int]): Int = {
  46. if (money == 0) 1
  47. else if (money < 0 || coins.isEmpty) 0
  48. else countChange(money - coins.head, coins) + countChange(money, coins.tail)
  49. }
  50. }
Add Comment
Please, Sign In to add comment