September 14, 2023

Solution for Advent of Code 2015 - Day 5: Doesn't He Have Intern-Elves For This?

 Link to the puzzle text

Part 1

Checking whether string conform to some arbitrary rules seems like a job for regexes. 
The first rule is to check if there are 3 or more vowels in the string. Checking for a single vowel can be done with [aieou], which checks if the string contains one out of the characters inside the brackets (the angular [] ). To check for 3 vowels, we copy the group 2 more times and fill the space between these groups with .* which checks for an arbitrary amount of characters. So together:
re.search("[aeiou].*[aeiou].*[aeiou].*", string_to_check)

The second rule is to check for a character to appear twice in a row. For this, we use the regex capture group (.) to get a single character and check if it appears right after again with \\1 . So together:

re.search("(.)\\1", string_to_check)

The third rule excludes strings with specific substrings, so similar to the first rule we just manually check for the simple existance of these substring:

re.search("(ab)|(cd)|(pq)|(xy)", string_to_check)

Once we have these three regexes, I wrote simple functions just to check if the string containst this regex.  The examples provided were used a sanity check. Afterwards we iterate over all lines in the input and count the string fulfilling all rules.

Part 2

Instead of the previous three rules, we now have to check for two other rules.
The new first rule is to check for two pairs of letters. Similar to the previous second rule we capture a group of two characters (..), allow an arbitrary amount of characters .* and check for our captured group again \\1 .
re.search("(..).*\\1", string_to_check) 
The new second rule is searching for two same characters separated by a single character. The regex look like the previous one, just with a single character in the capture group and only a single separation character allowed.
re.search("(.).\\1", string_to_check)

For the input we again iterate over all lines and count the number of strings fulfilling both rules.

Link to my solutions

No comments:

Post a Comment