Advertisement
jules0707

countChange

Feb 27th, 2017
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.10 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 || c == r) 1 else (pascal(c - 1, r - 1) + pascal(c, r - 1))
  18.  
  19.   /**
  20.    * Exercise 2
  21.    */
  22.   def balance(chars: List[Char]): Boolean = {
  23.     require(!chars.isEmpty)
  24.  
  25.     def countParentheses(chars: List[Char], acc: Int): Int = {
  26.       if (acc < 0) -1
  27.       else if (chars.isEmpty) acc
  28.       else countParentheses(chars.tail, acc + typeChar(chars.head))
  29.     }
  30.  
  31.     def typeChar(char: Char): Int = {
  32.       if (char == '\u0028') 1
  33.       else if (char == '\u0029') -1
  34.       else 0
  35.     }
  36.  
  37.     (countParentheses(chars, 0) >= 0)
  38.   }
  39.  
  40.   /**
  41.    * Exercise 3
  42.    */
  43.  
  44.   def countChange(money: Int, coins: List[Int]): Int = {
  45.     if (money < 0) 0
  46.     else if (money == 0) 1
  47.     else if (coins.isEmpty) 0
  48.     else (countChange(money - coins.head, coins) + countChange(money, coins.tail))
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement