3 ms·
If - guessing from the given example - the brackets problem only involves a single type of bracket, then the solution is micro-sized: OpenCount = 0 until
by bell-cot 4y ago
If - guessing from the given example - the brackets problem only involves a single type of bracket, then the solution is micro-sized:
OpenCount = 0
until( Exhausted( input ) ) {
if( NextChar( input ) == '(' )
OpenCount++
if( NextChar( input ) == ')' )
OpenCount--
if( OpenCount < 0 )
ERROR( "Negative Nesting Level in Input" )
IncrementPointer( input )
}
if( OpenCount != 0 )
ERROR( OpenCount." Unclosed Nesting Level(s) in Input" )
Print( "Nesting okay in Input" )
It took me <10 seconds to think up that algorithm, and I haven't written parsing code (that cared about such things) in years.
- ChuckNorris89 4y agoI think your algo just checks if there are exact number of open and closed brackets, but it doesn't check that they actually match together in a valid way.
- bell-cot 4y agoDo you mean input such as ")(" or "())("? (If so, that would trigger the "Negative Nesting Level" error.)
- monksy 4y agohttps://scastie.scala-lang.org/monksy/oHy8eviuTYeHCj0B8qSCJw/21 https://scastie.scala-lang.org/monksy/oHy8eviuTYeHCj0B8qSCJw... Could be improved as a collect.. but that was a first pass. [Did take some go overs to fix a few typos]