October 10, 2023

Solution for Advent of Code 2015 - Day 10: Elves Look, Elves Say

Link to the puzzle text

Part 1

In this puzzle, we implement the look-and-say-sequence. In this sequence, each term is replaced by a description of the previous term. To implement, we iterate over the string. Either we have the same character as last iteration. Then we increase our count by 1. Or it is a new character, then we reset the count to 1 and add the counter plus last character to the new sequence.
def look_and_say(string):
new_string = ""
num_repeats = 0
old_char = string[0]
for char in string:
if char == old_char:
num_repeats += 1
else:
new_string += str(num_repeats) + old_char
old_char = char
num_repeats = 1
new_string += str(num_repeats) + old_char
return new_string

This function is called 40 times in a row, starting with our puzzle input to get the answer.

Part 2

For part 2, we just increase the number of iterations to 50. Since the function was already fast enough, no additional programming was needed.

No comments:

Post a Comment