Part 1
In this puzzle, we have a list of characters describing a nested structure. There are multiple nested groups starting with an { and ending with an }. There can also be a garbage group noted by <>, which cannot be nested. Finally there is a ! character which escapes the next character. Each group is assigned a score based on its depth in the current structure and we should find the sum of all scores.
We can parse this struct from start to finish while keeping track of the current depth and all special groups. For that, we have a depth variable and two booleans for whether we should skip the next character (because we just read an "!") or if we are in a garbage group. Depending on these bools we read the next character one at a time and change our current mode. The score is updated whenever we leave a group.
for char in s:
if skip_next_char:
skip_next_char = False
continue
if in_garbage:
if char == ">":
in_garbage = False
elif char == "!":
skip_next_char = True
else:
if char == "{":
depth += 1
elif char == "}":
score += depth
depth -= 1
elif char == "<":
in_garbage = True
Part 2
In part 2, we should count the characters in all garbage groups.
We reused the code from part 1 and introduced a new variable for counting the garbage characters. If we are in the garbage mode and read a non-special character, we increase this count by one.
No comments:
Post a Comment