Part of Advent of Code Golf 2021 event. See the linked meta post for details.
Related to AoC2017 Day 9.
Weekends are Bubbler's days off from posting these lol
A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters.
You sit for a while and record part of the stream (the input). The characters represent groups - sequences that begin with {
and end with }
. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a }
only closes the most-recently-opened unclosed group - that is, they are nestable. The input represents a single group which itself may or may not contain smaller ones.
Sometimes, instead of a group, you will find garbage. Garbage begins with <
and ends with >
. Between those angle brackets, almost any character can appear, including {
and }
. Within garbage, <
has no special meaning.
In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !
: inside garbage, any character that comes after !
should be ignored, including <
, >
, and even another !
.
You don't see any characters that deviate from these rules. Outside garbage, you only find well-formed groups, and garbage always terminates according to the rules above.
The following are some example streams with the number of groups they contain:
{}
, 1 group.{{{}}}
, 3 groups.{{},{}}
, also 3 groups.{{{},{},{{}}}}
, 6 groups.{<{},{},{{}}>}
, 1 group (which itself contains garbage).{<a>,<a>,<a>,<a>}
, 1 group (containing four pieces of garbage).{{<a>},{<a>},{<a>},{<a>}}
, 5 groups.{{<!>},{<!>},{<!>},{<a>}}
, 2 groups (since all>
s except the last one are cancelled, creating one large garbage).{{<!!>,{<abc>},<!!!>>,{{<{!>}>},<yes<<<no>}},<>}
, 5 groups.
Input: A self-contained, well-formed group as a string.
Output: The total number of groups it contains, including itself.
Standard code-golf rules apply. The shortest code in bytes wins.
!
only cancels the single character after it? I think that it should be made clear that it's only the one character after!
that is ignored \$\endgroup\${{<>,<!!>}}, 2 groups
. My initial approach worked for all existing test cases, but not for this one (because I removed!>
before!!
, and therefore also incorrectly removed!}
). \$\endgroup\$