Advertisement
Guest User

Untitled

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