57
5
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.
Rules and definitions:
For the purpose of this challenge, a "bracket" is any of these characters:
()[]{}<>
.A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
() []{}
Or if every subelement inside of it is also matched.
[()()()()] {<[]>} (()())
Subelements can also be nested several layers deep.
[(){<><>[()]}<>()] <[{((()))}]>
A string is considered "Fully matched" if and only if:
Every single character is a bracket,
Each pair of brackets has the correct opening and closing bracket and in the right order, and
Each bracket is matched.
You may assume the input will only contain printable ASCII.
Test IO
Here are some inputs that should return a truthy value:
()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]
And here are some outputs that should return a falsy value:
( Has no closing ')'
}{ Wrong order
(<)> Each pair contains only half of a matched element
(()()foobar) Contains invalid characters
[({}<>)> The last bracket should be ']' instead of '>'
(((())) Has 4 opening brackets, but only 3 closing brackets.
As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.
1Related. – Martin Ender – 2016-04-05T06:42:29.840
7Note to potential close voters: The challenge I linked also includes a priority order for the bracket types so they cannot be nested in an arbitrary order. I think that makes it sufficiently different. – Martin Ender – 2016-04-05T06:55:36.153
Is
[}
a match? And if not, where is it excluded by these rules? – user207421 – 2016-04-05T13:13:42.3632@EJP No, it is not.
Each pair of brackets has the correct opening and closing bracket and in the right order.
– James – 2016-04-05T13:17:18.7506
I will upvote the first solution in Brackets
– leo – 2016-04-05T14:27:05.667Does no output (i.e. program not terminating) count as falsey? – Conor O'Brien – 2016-04-05T21:56:29.120
@CᴏɴᴏʀO'Bʀɪᴇɴ I think according to the consensus that would be undefined, so I'll say no. Although that might be worth a meta post.
– James – 2016-04-05T22:40:35.283@DrGreenEggsandHamDJ Thanks. I don't find that a clear enough statement, and I'm a compiler writer. – user207421 – 2016-04-05T22:56:06.397
When I saw the title I thought knew exactly who would be posting it, because DJMcMayhem invented Brain-flak. But I was surprised that this challenge was posted by James instead ... – a'_' – 2020-02-23T07:59:32.463