Skip to content

Instantly share code, notes, and snippets.

@DataKinds
Last active July 13, 2024 20:05
Show Gist options
  • Save DataKinds/e536fc6a11af6400c5a57c24e50efcfb to your computer and use it in GitHub Desktop.
Save DataKinds/e536fc6a11af6400c5a57c24e50efcfb to your computer and use it in GitHub Desktop.
NB. here's a validator that only works with parens
NB. call it with c d '())()()()()()()())))))(())()(()'
d=: +/\@(=&'(' + -@=&')') NB. paren nesting depth
c=: {{ */ (0&= {: y),(=&0 +/ <&0 y) }} NB. nesting depth validator
NB. here's a validator that works with all the paren types given
NB. by the spec at https://leetcode.com/problems/valid-parentheses/description/
NB. call it with isvalid '[()]{(()[]{})}'
identify=: (3&| ,. (<&3)) @ ('({[)}]'&i.) NB. returns (paren type, 0=open/1=close)
pop=: ((] {{throw. 'mismatched bracket'}})`(] }:)@.(= {:)) NB. x=paren type ({. @ identify), y=stack
push=: ,~ NB. x=paren type ({. @ identify), y=stack
stackit=: {{ ({.x) (pop`push)@.({:x) y }} NB. x=output of identify, y=stack
isvalid=: monad define
try.
a: -: {: (>a:) < F:. ((] identify)~ stackit ]) y
catcht.
0 return.
end.
)
isvalid '[()]{(()[]{})}'
isvalid '(]'
isvalid '[[[[))))'
isvalid '[(])'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment