You are a project manager. One day, one of your programmers went insane (not your fault) and took all the expressions in the codebase and added random brackets to them, before quitting on the spot, ranting about your incompetence (also not your fault). This would be an easy fix, however, for some reason you aren't using revision control (totally not your fault). And for some reason, none of the other programmers want to go through every expression to fix up the mismatched brackets (by the way, that is not your fault). Programmers these days, you think to yourself. You will have to do it yourself. The horror! Such tasks were supposed to be beneath you...
The input will be a single line, which will contain a number of left brackets (( [ {
) and right brackets () ] }
). It also may, but not always, contain comments (/* */
) and string literals (" "
or ' '
) and various numbers, letters, or symbols.
There will be at least one bracket (outside of a comment or string literal) that does not have a corrosponding opposite (outside of a comment or string literal). For example, an errant }
without a {
prior. Another example: a (
which does not have a )
afterwards. Your program will replace with a space the minimum number of brackets required to make the brackets match up.
Examples:
(4 + (2 + 3))]
==> (4 + (2 + 3))
(the square bracket at the end)
][][[]]
==> [][[]]
(the square bracket at the start)
("Hel(o!"))
==> ("Hel(o!")
(the parenthesis at the end)
( /* )]*/
==> /* )]*/
(the parenthesis at the start)
{()]
==> ()
(the curly bracket and the square bracket)
- Input can be taken from whichever way is most convenient (STDIN, command line argument, reading from a file, etc.)
- If there is more than one way to resolve the mismatch with the same number of removals, either is acceptable.
- There will be only mismatches in brackets. String literals and comments will always be correctly formed.
- The title comes from this SO thread
- There will never be any quotes in comments, quotes in quotes, comments in comments, or comments in quotes.
This is code golf, so minimum number of bytes wins. Ask questions in comments if the specification is not clear.
("foo (\") bar")
)? \$\endgroup\${{(})
should be{ }
or equivalent, since the opening scenario implies that the code was working to begin with, and{(})
counts as mismatched brackets in every programming language I know (i.e. "causes stasis"??). But, then, I already wrote an answer, so I'm biased. \$\endgroup\$