Just a few interesting pieces of Scala code
Last active
November 19, 2022 16:54
-
-
Save jasonicarter/63ddf092750c9493dfc546f151e14189 to your computer and use it in GitHub Desktop.
Counting change recursive algorithm in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def balance(chars: List[Char]): Boolean = { | |
def loop(chars: List[Char], stack: Int): Boolean = { | |
if (chars.isEmpty) stack == 0 // '(' and ')' should result in 0 if balanced | |
else if (chars.head == '(') loop(chars.tail, stack + 1) | |
else if (chars.head == ')') loop(chars.tail, stack - 1) | |
else loop(chars.tail, stack) | |
} | |
if (chars.isEmpty) true // if empty, debatable as balanced | |
else if (chars.head == chars.last) false // if head and last are equal brackets not balanced | |
else loop(chars, 0) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def countChange(money: Int, coins: List[Int]): Int = { | |
def loop(money: Int, coins: List[Int]): Int = { | |
if (money < 0 || coins.isEmpty ) 0 | |
else if (money == 0 ) 1 | |
else loop(money, coins.tail) + loop(money - coins.head, coins) | |
} | |
loop(money, coins) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum(xs: List[Int]): Int = { | |
def loop(xs: List[Int], prevHead: Int): Int = { | |
if (xs.isEmpty) 0 | |
else if (xs.tail.isEmpty) xs.head+prevHead | |
else loop(xs.tail, xs.head+prevHead) | |
} | |
loop(xs, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
balance("())(()")
returns true, which is not correct.Here is my solution: