Skip to content

Instantly share code, notes, and snippets.

@jjst
Created March 21, 2016 20:53
Show Gist options
  • Save jjst/e3a1ddaa37217be6bf87 to your computer and use it in GitHub Desktop.
Save jjst/e3a1ddaa37217be6bf87 to your computer and use it in GitHub Desktop.
/**
* Created by jjst on 21/03/16.
*/
object Floors {
def main(args: Array[String]): Unit = {
Console.println(floorNumber1("())"))
Console.println(floorNumber2("())"))
Console.println(floorNumber2(""))
}
def floorNumber1(str: String): Int = floorNumber1(str.toList)
def floorNumber1(str: List[Char]): Int = str match {
case firstParens :: rest => firstParens match {
case '(' => 1 + floorNumber1(rest)
case ')' => -1 + floorNumber1(rest)
}
case Nil => 0
}
def floorNumber2(str: String): Int = floorNumber2(str.toList)
def floorNumber2(str: List[Char]): Int = {
str.map { char: Char => char match {
case '(' => 1
case ')' => -1
}
}.sum
}
def floorNumber3(str: List[Char]): Int = {
str.foldLeft(0) { (i: Int, c: Char) =>
val j = if(c == '(') 1 else -1
i + j
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment