Welcome to my solution walk-through for Day 1 of the Advent of Code challenge, titled “Trebuchet?!”. This year, you are tasked with restoring global snow production, which requires getting fifty stars marked on a map by December 25th.
The elves are loading you onto a trebuchet, ready to shoot you into the sky, because that’s where the snow comes from. But here’s the catch: the calibration document needed for the trebuchet has been creatively altered by a young Elf, making the values hard to read. This sets the stage for our two-part programming challenge:
This puzzle tests our ability to manipulate strings, regular expressions, and map data structures. It’s an excellent exercise in parsing and transforming textual data.
def solve():
"""Solve first part of the puzzle"""
# only keep the digits of each line
numbers = input(convert_fn=lambda s: "".join(filter(str.isdigit, s)))
# concat first and last digit, convert to int, calculate sum
return sum(map(int, [n[0]+n[-1] for n in numbers if n]))
def solve2():
"""Solve second part of the puzzle"""
# produce a map for different string representations to ints (e.g. 'one': 1, '1': 1)
str_digit_map = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
str_digit_map = {s: str(i) for i, s in enumerate(str_digit_map, start=1)}
str_digit_map.update({str(i): str(i) for i in range(1, 10)})
result = 0
for line in input():
# in each line find the starting indices for each number string
findings = {}
for s, v in str_digit_map.items():
findings.update({i: v for i in substring_idx(line, s)})
# the minimum and maximum indices correspond to the first and last digit in the string
min_idx, max_idx = min(findings), max(findings)
# concat digits and sum up
result += int("".join((findings[min_idx], findings[max_idx])))
return result
The function to find all starting indices of a substring can be easily implemented using the re module:
Reflecting on this year’s Advent of Code, Day 1’s “Trebuchet?!” puzzle stands out as a notch more challenging compared to the puzzles of previous years. Particularly, the second part of the challenge brought an intriguing twist that compelled me to rethink my initial approach.
My first instinct was to employ simple string replacements to extract and process the digits. While this method seemed straightforward initially, it quickly became apparent that it wasn’t sufficient for the task at hand, especially when dealing with concatenated digit words like ‘eightwothree’.