Created
April 20, 2016 23:57
-
-
Save inakianduaga/e4d7fdce06d2bc1e56fd93d1c1137f62 to your computer and use it in GitHub Desktop.
Coursera Scala Functional Programming 1st Week balance brackets
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
/** | |
* Criteria: Every closing parenthesis ) must have a unique opening ( parenthesis before it | |
* | |
* For every closing parenthesis, we search for the first opening parenthesis and remove it, and keep going | |
*/ | |
def balance(chars: List[Char]): Boolean = | |
(chars.indexOf(')'), chars.indexOf('(')) match { | |
case (leftMostClosing, leftMostOpening) if leftMostClosing == -1 && leftMostOpening != -1 => false // no closing / some opening => fail | |
case (leftMostClosing, leftMostOpening) if leftMostClosing == -1 && leftMostOpening == -1 => true // no closing or opening => ok | |
case (leftMostClosing, leftMostOpening) if leftMostClosing != 1 && leftMostOpening == -1 => false // closing but no opening => fail | |
case (leftMostClosing, leftMostOpening) if leftMostClosing != -1 && leftMostOpening != -1 // first closing before first opening | |
&& leftMostClosing < leftMostOpening => false | |
case (leftMostClosing, leftMostOpening) => balance( // first closing after first opening => strip them and recurse | |
chars | |
.zipWithIndex | |
.filter(tuple => tuple._2 != leftMostClosing && tuple._2 != leftMostOpening) | |
.map(tuple => tuple._1) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the end it looks like your solution, the generalization to a list of symbols is trivial