One-pass version:

pairs =. _2 ]\ '()[]{}'
remnant =: (2&}.)^:(pairs e.~ 2&{.)@,/@(#~ e.&(,pairs))
balanced =: (+&(*...@#) -.&({."1 pairs))@remnant

Henry Rich


Henry Rich wrote:
> This removes inner matched pairs repeatedly and analyzes what's left. 
> Suitable if the nesting level is not very high.  Should be 3 lines.
> 
> pairs =. _2 ]\ '()[]{}'
> remnant =: (#~   [: (+: _1&(|.!.0)) [: +./ pairs&(E."1))^:_ @ (#~ 
> e.&(,pairs))
> balanced =: ( *...@# + *...@#@(-.&({."1 pairs)) )@remnant
> 
>     balanced '()[]'
> 0
>     balanced '()[]('
> 1
>     balanced '()[](]'
> 2
> 
> Henry Rich
> 
> Chris Burke wrote:
>> How to check if a string has balanced [] {} ()?
>>
>> Any pair by itself is easy enough, but I want to check all three balance 
>> together, e.g.
>>
>>    ...[(])...
>>
>> would fail. Assume there are no character strings.
>>
>> Ideally, I'd like a result of
>>
>>    0 = balanced
>>    1 = balanced so far, but some closing delimiters to come
>>    2 = unbalanced (and broken)
>>
>>
>> ----------------------------------------------------------------------
>> For information about J forums see http://www.jsoftware.com/forums.htm
>>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
> 
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to