Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Last active December 28, 2015 01:39
Show Gist options
  • Save animatedlew/7421766 to your computer and use it in GitHub Desktop.
Save animatedlew/7421766 to your computer and use it in GitHub Desktop.
Iterates through a string of characters and returns true if the input contains a balanced set of parentheses.
package practice
object SymbolBalancer extends App {
val data: List[String] = List(
"(if (zero? x) max (/ 1 x))",
"I told him (that it's not (yet) done). (But he wasn't listening)",
":-)",
"())(",
"((d)o(n)e)",
")(")
/**
* Iterates through a string of characters and returns true
* if the input contains a balanced set of parentheses
*/
def balance(chars: List[Char]): Boolean = {
// This accumulates the result by or-ing the result. Once this evals to true, it will stay true
def isMismatched(balanced: Boolean, total: Int, pred: Int => Boolean) = !balanced || pred(total)
def isNeg(num: Int): Boolean = num < 0
def findMatch(list: List[Char], isBalanced: Boolean = true, total: Int = 0): Boolean = {
// If the total is positive and the string is balanced, hence no mismatch
val balanced = !isMismatched(isBalanced, total, isNeg)
if (list.isEmpty) balanced
else if (list.head == '(') {
findMatch(list.tail, balanced, total + 1)
} else if (list.head == ')') {
findMatch(list.tail, balanced, total - 1)
} else {
findMatch(list.tail, balanced, total)
}
}
findMatch(chars)
}
println("Balancing Parentheses")
println("---------------------")
data.foreach(str => {
println("isBalanced? " + balance(str.toList) + "\n\"" + str + "\"\n")
})
}
/*
Balancing Parentheses
---------------------
isBalanced? true
"(if (zero? x) max (/ 1 x))"
isBalanced? true
"I told him (that it's not (yet) done). (But he wasn't listening)"
isBalanced? false
":-)"
isBalanced? false
"())("
isBalanced? true
"((d)o(n)e)"
isBalanced? false
")("
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment