Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

# Advent of Code - 2023

This is a solution to Day 1 of Advent of Code 2023.

# Day 1 - Trebuchet?!

Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems.

You've been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th.

Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

You try to ask why they can't just use a weather machine ("not powerful enough") and where they're even sending you ("the sky") and why your map looks mostly blank ("you sure ask a lot of questions") and hang on did you just say the sky ("of course, where do you think snow comes from") when you realize that the Elves are already loading you into a trebuchet ("please hold still, we need to strap you in").

As they're making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document.

The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.

## Reading the input

As every day, we start by reading in the input with our helper function. Since our input today is strings, we don't need to do any conversions and can read it with `read_input(1)``.

``````from utils import read_input

``````

## Part 1

For example:

``````1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
``````

In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.

Consider your entire calibration document. What is the sum of all of the calibration values?

To solve this, I'm using regular expressions which are a powerful way to find patterns in strings.

For each calibration string, I find all the numbers (`\d` means "any single digit") with re.findall, then concatenate them into a single number with f-strings and convert to an integer.

In Python, you can index lists with numbers where 0 is the first index. With negative values, you start reading the list from the end so -1 gives us the last value.

``````import re

def recalibrate(calibrations):
result = 0
for calibration in calibrations:
numbers = re.findall(r'\d', calibration)
calibration_value = int(f'{numbers[0]}{numbers[-1]}')
result += calibration_value
return result
``````
``````part_1 = recalibrate(calibrations)
print(f'Solution: {part_1}')
assert part_1 == 54632
``````

## Part 2

Your calculation isn't quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid "digits".

Equipped with this new information, you now need to find the real first and last digit on each line. For example:

``````two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
``````

In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.

What is the sum of all of the calibration values?

This second part gave me a bit of a headache as I was getting an incorrect number despite everything initially looking good. It turned out, there were overlaps within those number strings (for example, `eightwo`) with which my initial regex (`\d|one|two|three|four|five|six|seven|eight|nine`) only found the first one.

For the solution, there are two main changes:

First, I changed the regex pattern to also include each of the allowed word numbers and I used a lookahead assertion (`?=`) to make sure my regex found all the matches, not only the ones that first appear in these overlaps.

Second change was to create a `convert_to_int` function that takes a string that is either a number ('1-9') or one of those word numbers ('one-nine') and converts it to an integer. To do that, I rely on two mechanics. First, I created a list with these word numbers (including `zero` which is not an allowed value in this exercise but pads out the indices nicely) and then I try to convert the string to integer with `int()` and if that fails because `numberish` is not a valid number, I find its correct index with `.index()` method.

This `convert_to_int` function will fail if its passed anything that is not a number nor on that list. If I were to write it in a real environment, I'd add some more error handling but since it's a puzzle and we're guaranteed by our regex earlier to only pass valid values, I'll let it be as it is.

``````def convert_to_int(numberish):
"""
Takes a string that is either a numeric value (0-9) or
one of the single digit values written as words.

Converts the number into a Python integer.

Throws ValueError if the argument is none of the
valid values.
"""
names_to_values = [
'zero', 'one', 'two',
'three', 'four', 'five',
'six', 'seven', 'eight',
'nine'
]
try:
return int(numberish)
except ValueError:
return names_to_values.index(numberish)

def calibrate_p2(calibrations):
result = 0
for calibration in calibrations:
numbers = re.findall(r'(?=(\d|one|two|three|four|five|six|seven|eight|nine))', calibration)
first, last = convert_to_int(numbers[0]), convert_to_int(numbers[-1])
calibration_value = int(f'{first}{last}')
result += calibration_value
return result
``````
``````part_2 = calibrate_p2(calibrations)
print(f'Solution: {part_2}')
assert part_2 == 54019
``````

## Two stars!

First day in the bag with full two stars ⭐️⭐️