Advertisement
Guest User

Untitled

a guest
May 28th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 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.  
  18. if(c == 0 || r == 1) 1 else pascal(c - 1, r) + pascal(c, r - 1)
  19. }
  20.  
  21. /**
  22. * Exercise 2
  23. */
  24. def balance(chars: List[Char]): Boolean = {
  25. def getWeight(c: Char): Int = {
  26. val weight = Map(
  27. '(' -> 1,
  28. ')' -> -1
  29. )
  30. if(weight isDefinedAt c) weight(c) else 0
  31. }
  32.  
  33. def balanceIter(chars: List[Char], n: Integer): Boolean = {
  34. if(chars.isEmpty) n == 0
  35. else if(n<0) false
  36. else balanceIter(chars.tail, n + getWeight(chars.head))
  37. }
  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) 0
  47. else if(money == 0) 1
  48. else {
  49. countChange(money - coins.head, coins) + countChange(money, coins.tail)
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement