August 04, 2024

Solution for Advent of Code 2017 - Day 1: Inverse Captcha

Link to the puzzle text

Part 1

In this puzzle, we are given a string and need to sum all digits equal to the next digit. At the end, the string wraps around. So 1122 turns into 1 (the first and second digit are the same) + 0 (the second and third digit are different) + 2 (the third and fourth digit are the same) + 0 (the second and third digit are different) = 3.

We first create the string to compare to by starting one position later than normal and adding the first position and the end.

lookahead_string = string[1:] + string[0]

We can compare the original and the lookahead string elementwise and keep only elements that are the same.

[char for char, comp in zip(string, lookahead_string) if char == comp]

 The filtered elements are converted into numbers and summed up.

Part 2

For part 2, we compare each digit to the digit halfway around the string instead of the next digit. The wrapping around still functions as normal.

For this, we change the construction of the lookahead string into

lookahead_string = (string + string)[lookahead:len(string) + lookahead]

The variable lookahed is set elsewhere to len(string) / 2. The rest of the previous solution can stay the same.

Link to my solutions

No comments:

Post a Comment