January 20, 2025

Solution for Advent of Code 2018 - Day 5: Alchemical Reduction

Link to the puzzle text

Part 1

In this puzzle we have a long string of both lower- and uppercase letters. We are asked to reduce the string by the following method: Whenever a lowercase character is next to its uppercase version (like 'aA'), delete both from the string. This should be done until no further actions are possible. The answer is the length of the final string.

To solve, we took each character and  replaced both possible combinations from the string:

for char in string.ascii_lowercase:
    line = line.replace(char + char.upper(), "")
    line = line.replace(char.upper() + char, "")

This was done in an loop until no further replacements were done.

Part 2

In part 2, we should repeat the reduction above on slightly different strings: The input without any 'a's, without any 'b's, ... One of these strings reduces to the lowest number and we should return this minimal length.

We reused the previous reduction function and supplied different inputs to it.

lengths = []
for char in string.ascii_lowercase:
up = char.upper()
length = len_after_reducing(line.replace(char, "").replace(up, ""))
lengths.append(length)
print(min(lengths))

Link to my solutions

No comments:

Post a Comment