October 16, 2023

Solution for Advent of Code 2015 - Day 11: Corporate Policy

Link to the puzzle text

Part 1

For this puzzle, we need to iterate over possible strings until we find one matching all three rules. Increasing the string from one iteration to the next is done similar to counting up. We increase the last position until we reach "z". Then we reset the position to "a" and increase the position one to the left.

def increment_string(string, pos=1):
char_to_increment = string[-pos]
if char_to_increment == "z":
string[-pos] = "a"
return increment_string(string, pos + 1)
else:
string[-pos] = chr(ord(char_to_increment) + 1)
return string

To check if a string can be accepted, we have to check three rules. The first requires 3 consequent letters in the string, so "abc" or "tuv". The function for that is naively written by iterating over all characters, constructing the sequence and checking for its presence. If we reach the end and have not found a sequence yet, we fail the rule.
The second rule just checks if there is a "i", "o" or "l" letter in the string.
The third rule requires two pairs of adjecent same letters. We check this via the regex "(.)\\1.+(.)\\2". Similar to day 5, we first capture a single character via (.) and its repeat \\1. This is repeated for another character and another repeat \\2.

Once the checks are written we iterate over all strings until we find the solution. This can probabily be sped up by skipping over forbidden chars in the increasing process, but it was fast enough.

Part 2

For part 2, we need to repeat the process again after finding the previous answer. This took a bit more time, but still only seconds. So no further optimization was needed.

No comments:

Post a Comment