Day 1: Trebuchet?! #
Part 1 #
The Problem #
The input is comprised of lines of text where each line contains a “calibration value”. To find the calibration value in each line, find the first and last digit contained on each line. The first and last number of each line will form a two digit number. The answer is the sum of every two digit number.
For example:
1abc2
pqr3sty8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
What is the sum of all of the calibration values?
Insights #
It is possible for the first and second digit of a given line to be at the same position.
example8string
The first digit of the string is 8. The last digit of the string is the same 8.
Solutions #
input = '' # Puzzle input here
def solution(input):
sum = 0
for line in input.split('\n'):
number = 0
for char in line:
if char.isnumeric():
number += int(char)*10
break
for char in reversed(line):
if char.isnumeric():
number += int(char)
break
sum += number
return sum
import cvs
while True:
print('Someone Else!')
Part 2 #
The Problem #
Now you must consider numbers that are not only represented by digits, but also as english words. The words: “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, and “nine”, now also count as digits.
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
vzoneight234
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?
Insights #
Words can overlap
xnineightx
The words “nine” and “eight” overlap, but still count as individual numbers. The calibration number of the example is 98.
Solutions #
def part2(puzzle_input):
def word_to_digit(match_obj):
match match_obj.group(1):
case 'one': return 1
case 'two': return 2
case 'three': return 3
case 'four': return 4
case 'five': return 5
case 'six': return 6
case 'seven': return 7
case 'eight': return 8
case 'nine': return 9
case _: return int(match_obj.group(1))
total = 0
for line in puzzle_input.split():
match_iter = re.finditer(r'(?=(one|two|three|four|five|six|seven|eight|nine|\d))', line)
only_digits = [word_to_digit(i) for i in match_iter]
total += only_digits[0] * 10 + only_digits[-1]
return total