From 26f76f606f7b050c4d0ace29ac79f6688c2121e8 Mon Sep 17 00:00:00 2001 From: beauvill Date: Tue, 24 Sep 2019 15:54:38 +0200 Subject: [PATCH] Created Pascal, Balance and countChange functions --- src/main/scala/recfun/RecFun.scala | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/scala/recfun/RecFun.scala b/src/main/scala/recfun/RecFun.scala index 4a2b054..dc11b25 100644 --- a/src/main/scala/recfun/RecFun.scala +++ b/src/main/scala/recfun/RecFun.scala @@ -9,18 +9,36 @@ object RecFun extends RecFunInterface { print(s"${pascal(col, row)} ") println() + + /** * Exercise 1 */ - def pascal(c: Int, r: Int): Int = ??? + def pascal(c: Int, r: Int): Int = + if (c == 0 || c == r) then 1 + else pascal(c-1,r-1) + pascal(c,r-1) /** * Exercise 2 */ - def balance(chars: List[Char]): Boolean = ??? + def balance(chars: List[Char]): Boolean = { + def checkParenthesis(chars: List[Char], opened: Int): Boolean = + if (chars.isEmpty) then opened == 0 + else if (opened < 0) then false + else if (chars.head == '(') then checkParenthesis(chars.tail, opened + 1) + else if (chars.head == ')') then checkParenthesis(chars.tail, opened - 1) + else checkParenthesis(chars.tail, opened) + + checkParenthesis(chars, 0) + } + /** * Exercise 3 */ - def countChange(money: Int, coins: List[Int]): Int = ??? + def countChange(money: Int, coins: List[Int]): Int = + if(money == 0) then 1 + else if(money < 0) then 0 + else if(coins.isEmpty) then 0 + else countChange(money - coins.head, coins) + countChange(money, coins.tail) }