January 31, 2024

Solution for Advent of Code 2016 - Day 7: Internet Protocol Version 7

Link to the puzzle text

Part 1

In this puzzle, we are asked to validate strings according to a rule. The strings are divided into parts inside and outside of square brackets []. Outside the brackets, a string should contain a pair of two different characters followed by the reversed pair. Inside of brackets there should be no such pair. If this is true, a string is valid.

First we wrote a function checking a substring if it contains a pair followed by the reversed pair. This is mostly done by the regex (.)(.)\2\1. The groups in round brackets () is captured and later referenced either by \1 or \2. We then have to check if the pair has different characters.

def contains_abba(group):
if matches := re.findall(r"(.)(.)\2\1", group):
for m in matches:
if m[0] != m[1]:
return True
return False

We then split our string into inside and outside of brackets with the re.split("[\[\]", line). Starting with 0, every second group is now outside of brackets. The check if any if these groups fulfill the function above. Additionally all of the other groups have to not fulfill the function.

any([contains_abba(g) for g in groups[::2]])
    and all([not contains_abba(g) for g in groups[1::2]])

Part 2

The rule to fulfill is now to check for an a-b-a triplet outside of brackets where there is an b-a-b triplet inside the brackets.

We first split the string in outside and inside of brackets again. The outside groups are checked for triplets. We then create a regex pattern for each of these triplets consisting of the reversed triplets inside brackets. If the full line contains this pattern, we count this line as valid.

tuples = zip(group, group[1:], group[2:])
abas = [b + a + b for a, b, c in tuples if a == c and a != b]
for aba in abas:
if re.search(f"\[[^\]]*{aba}[^\]]*\]", line):
valid_line = True

Link to my solutions

No comments:

Post a Comment