tdudzik

Untitled

Oct 13th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.40 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
  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.     def balanceRec(chars: List[Char], balance: Int): Int= {
  26.       if (balance < 0 || chars.isEmpty) return balance
  27.       val head = chars.head
  28.       if (head.equals('(')) balanceRec(chars.drop(1), balance + 1)
  29.       else if (head.equals(')')) balanceRec(chars.drop(1), balance - 1)
  30.       else balanceRec(chars.drop(1), balance)
  31.     }
  32.  
  33.     balanceRec(chars, 0) == 0
  34.   }
  35.  
  36.   /**
  37.     * Exercise 3
  38.     */
  39.   def countChange(money: Int, coins: List[Int]): Int = {
  40.     if (money == 0) return 0
  41.     if (coins.isEmpty) return 0
  42.  
  43.     def maxPossibleFactorExists(n: Int): Boolean = {
  44.       coins.exists(x => x <= money)
  45.     }
  46.  
  47.     def maxPossibleFactor(n: Int): Int = {
  48.       coins.filter(x => x <= money).max
  49.     }
  50.  
  51.     if (!maxPossibleFactorExists(money)) return 0
  52.  
  53.     val max = maxPossibleFactor(money)
  54.     if (max == money) 1 + countChange(money - max, coins)
  55.     else 1 + countChange(max, coins) + countChange(money - max, coins)
  56.   }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment