Skip to content

Commit b86c95c

Browse files
committed
Refactor 2025 day 6 to transpose text
1 parent d640e96 commit b86c95c

File tree

2 files changed

+30
-20
lines changed

2 files changed

+30
-20
lines changed

2025/python/src/aoc2025/day06.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import itertools
12
import math
23
from pathlib import Path
34

@@ -27,34 +28,30 @@ def part_1(input: Path) -> int:
2728

2829

2930
def part_2(input: Path) -> int:
30-
text = [[c for c in line] for line in input.read_text().splitlines()]
31-
len_longest_line = max(len(line) for line in text)
32-
text = [line + [" "] * (len_longest_line - len(line)) for line in text]
31+
text = transpose_text(input.read_text())
3332

3433
answers = []
3534
this_problem_numbers = []
36-
for col in range(len(text[0]) - 1, -1, -1):
37-
number: int | None = None
38-
operator: str | None = None
39-
for row in range(len(text)):
40-
char = text[row][col]
41-
if char.isnumeric():
42-
if number is None:
43-
number = int(char)
44-
else:
45-
number = 10 * number + int(char)
46-
elif char != " ":
47-
operator = char
48-
if number is not None:
49-
this_problem_numbers.append(number)
50-
if operator is not None:
51-
match operator:
35+
for line in reversed(text.splitlines()):
36+
if not line:
37+
continue
38+
if line.endswith("+") or line.endswith("*"):
39+
this_problem_numbers.append(int(line[:-1]))
40+
match line[-1]:
5241
case "+":
5342
answers.append(sum(this_problem_numbers))
5443
case "*":
5544
answers.append(math.prod(this_problem_numbers))
5645
case _:
57-
raise ValueError(f"Invalid operator: {operator}")
46+
raise ValueError(f"Invalid operator: {line[-1]}")
5847
this_problem_numbers = []
48+
else:
49+
this_problem_numbers.append(int(line))
5950

6051
return sum(answers)
52+
53+
54+
def transpose_text(s: str) -> str:
55+
lines = s.splitlines()
56+
transposed_lines = itertools.zip_longest(*lines, fillvalue=" ")
57+
return "\n".join("".join(line).rstrip() for line in transposed_lines)

2025/python/tests/test_day06.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@
55
DATA_DIR = Path(__file__).parent.parent / "data/day06"
66

77

8+
def test_transpose_text():
9+
assert (
10+
day06.transpose_text("""\
11+
ab
12+
cde
13+
f""")
14+
== """\
15+
ac
16+
bdf
17+
e"""
18+
)
19+
20+
821
def test_part_1(benchmark):
922
assert day06.part_1(DATA_DIR / "example.txt") == 4277556
1023
assert benchmark(lambda: day06.part_1(DATA_DIR / "input.txt")) == 3525371263915

0 commit comments

Comments
 (0)