Long overdue update - Functional programming in scala

Its been a while since i managed to get the time post on my blog, I've been really busy with work and home life,
I've recently enrolled in an online course. Functional programming in Scala.
I haven't really touched upon much function programming (except for javascript and a bit of F#). I like it! And i can see its uses! It feels a bit weird entering back into the java world, firing up eclipse etc. I guess i have just become  reliant on the friendly features of Visual Studio.

Anyway, here are the answers to the assignment I just submitted for the Functional Programming in Scala!

Pascals Triangle
  1.   def pascal(c: Int, r: Int): Int =
  2.     if (c == 0 || r == c) 1
  3.     else (pascal(c - 1, r - 1) + pascal(c, r - 1));
Parentheses Balancing
  1. def balance(chars: List[Char]): Boolean = {
  2.     def countParenthese(index: Int, list: List[Char]): Boolean = {
  3.       if (index == 0 && list.isEmpty) true
  4.       else if (index < 0 || list.isEmpty) false
  5.       else if (list.head == '(') countParenthese(index + 1, list.tail)
  6.       else if (list.head == ')') countParenthese(index - 1, list.tail)
  7.       else countParenthese(index, list.tail)
  8.     }
  9.     countParenthese(0, chars)
  10.   }
Change Counting
  1.  def countChange(money: Int, coins: List[Int]): Int =
  2.     if (money == 0) 1
  3.     else if (money < 0 || coins.isEmpty) 0
  4.     else countChange(money, coins.tail) + countChange(money - coins.head, coins)
  5. }


0 mentions:

Post a Comment