AdSense

Wednesday, August 26, 2015

Scala note 1: Pascal’s Triangle, Parentheses Balancing and Counting Change

I decided to take a look on Scala, so that next time I read a source code, at least I know what I am reading.

I choose Coursera's Functional Programming Principles in Scala as my reference (I do wish they open the class again, however, the same time when they open the class last year, I was fighting with Java 😞.)

First week's class are basics. Two concepts need to be remember:

Call by value: evaluates function arguments before calling the functionCall by name: evaluates the function first, and then evaluate the arguments if needed
Scala usually do call by value, but we can also do call by name by adding x: => Type to the parameter. 
All three exercise problems are about recursions. The algorithms are easy since those are problems we see all the time. 

Pascal's Triangle
The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a function that computes the elements of Pascal’s triangle by means of a recursive process.Do this exercise by implementing the pascal function in Main.scala, which takes a column c and a row r, counting from 0 and returns the number at that spot in the triangle. For example, pascal(0,2)=1pascal(1,2)=2 and pascal(1,3)=3.def pascal(c: Int, r: Int): Int

def pascal(c: Int, r: Int): Int = {
    if  (c == 0 || c == r || r == 0)  1
    else
      pascal(c - 1, r - 1) + pascal(c, r - 1)
  }

Sort of short...


Parentheses Balancing
Write a recursive function which verifies the balancing of parentheses in a string, which we represent as a List[Char] not a String. For example, the function should return true for the following strings:
  • (if (zero? x) max (/ 1 x))
  • I told him (that it’s not (yet) done). (But he wasn’t listening)
The function should return false for the following strings:
  • :-)
  • ())(
The last example shows that it’s not enough to verify that a string contains the same number of opening and closing parentheses.Do this exercise by implementing the balance function in Main.scala. Its signature is as follows:def balance(chars: List[Char]): Boolean
def balance(chars: List[Char]): Boolean = {
    def balance(chars: List[Char], left: Int): Boolean ={
      if(chars.isEmpty) left == 0
      else
        if (chars.head == ')') {left > 0 && balance(chars.tail, left - 1)}
        else if (chars.head == '(') {balance(chars.tail, left + 1)}
        else {balance(chars.tail, left)} 
    }
    balance(chars, 0)
  }

Basically, we count the left parenthesis ("(") . Each time there is a "(", we increment left. If there is a ")" and if left >0, then it is imbalanced, otherwise decrease left and check the substring. 

Counting Change
Write a recursive function that counts how many different ways you can make change for an amount, given a list of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomiation 1 and 2: 1+1+1+1, 1+1+2, 2+2.Do this exercise by implementing the countChange function in Main.scala. This function takes an amount to change, and a list of unique denominations for the coins. Its signature is as follows:def countChange(money: Int, coins: List[Int]): Int


def countChange(money: Int, coins: List[Int]): Int = {
    def countChange(money:Int, coins: List[Int], count:Int): Int = {
      if (money < 0) count
      else
        if (coins.isEmpty) 
          if (money == 0) count + 1 else count
        else
          countChange(money - coins.head, coins, count) + countChange(money, coins.tail, count)
    }
    countChange(money, coins, 0)
  }

To count all possibilities, we need to iterate all denominations in coins. Using recursion, it is the count of using coins[0] plus the count of not using coins[0], and recursively check all the denominations.


Source on git

1 comment:

  1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. IEEE final year projects on machine learning In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    ReplyDelete