Skip to content

Commit

Permalink
Solve day 1 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
mjalkio committed Dec 2, 2023
1 parent c7740fc commit 3f0cc70
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
7 changes: 7 additions & 0 deletions year_2023/day01/test_input_2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
7 changes: 7 additions & 0 deletions year_2023/day01/test_trebuchet.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@

def test_sum_calibration_values():
assert sum_calibration_values(read_puzzle_input("test_input.txt")) == 142


def test_sum_calibration_values_part_2():
assert (
sum_calibration_values(read_puzzle_input("test_input_2.txt"), parse_words=True)
== 281
)
32 changes: 29 additions & 3 deletions year_2023/day01/trebuchet.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
from util import read_puzzle_input


def sum_calibration_values(puzzle_input):
DIGITS = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}


def _get_digit(value, idx):
if value[idx].isdigit():
return value[idx]
for length in [3, 4, 5]:
if value[idx : idx + length] in DIGITS:
return DIGITS[value[idx : idx + length]]


def sum_calibration_values(puzzle_input, parse_words=False):
answer = 0
for value in puzzle_input.split("\n"):
digits = [c for c in value if c.isdigit()]
if parse_words:
digits = [
_get_digit(value, i) for i in range(len(value)) if _get_digit(value, i)
]
else:
digits = [c for c in value if c.isdigit()]
answer += int(digits[0] + digits[-1])
return answer

Expand All @@ -13,4 +39,4 @@ def sum_calibration_values(puzzle_input):
puzzle_input = read_puzzle_input()

print(f"Part 1: {sum_calibration_values(puzzle_input)}")
print(f"Part 2: {sum_calibration_values(puzzle_input)}")
print(f"Part 2: {sum_calibration_values(puzzle_input, parse_words=True)}")

0 comments on commit 3f0cc70

Please sign in to comment.