Skip to content

Commit ea97d3b

Browse files
committed
Solution: Day 7 - part 1 & 2
1 parent 88ae4bf commit ea97d3b

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

solutions/2025/7/main.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# 'Advent of code' solution for year 2025 day 7
2+
import os
3+
import sys
4+
5+
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
6+
7+
def _get_input():
8+
content = None
9+
if os.path.isfile(os.path.join(DIR_PATH, "input.txt")):
10+
with open(os.path.join(DIR_PATH, "input.txt"), "r", encoding="utf-8") as file:
11+
content = file.read().strip().splitlines()
12+
return content
13+
else:
14+
print("Error! Input file does not exist!")
15+
sys.exit()
16+
17+
def part_1(i: list[str]):
18+
result = 0
19+
curr = set()
20+
21+
curr.add(i[0].find("S"))
22+
for line_i, line in enumerate(i[1:], 1):
23+
new_curr = set()
24+
for index in curr:
25+
if line[index] == '^':
26+
if index-1 >= 0 and line[index-1] == ".": # split left
27+
line = line[:index-1] + "|" + line[index:]
28+
new_curr.add(index-1)
29+
if index+1 <= len(line) and line[index+1] == ".": # split right
30+
line = line[:index+1] + "|" + line[index+2:]
31+
new_curr.add(index+1)
32+
result+=1
33+
elif i[line_i][index] == ".":
34+
line = line[:index] + "|" + line[index+1:]
35+
new_curr.add(index)
36+
curr = new_curr
37+
i[line_i] = line
38+
39+
# print("\n".join(i), "\n")
40+
41+
print(f"[P1] Beam was split {result} times")
42+
43+
def part_2(i: list[str]):
44+
found: dict[tuple[int, int], int] = {}
45+
splitters: dict[int, list[int]] = {}
46+
47+
for y, line in enumerate(i):
48+
for x, val in enumerate(line):
49+
if val == "^":
50+
if x not in splitters:
51+
splitters[x] = []
52+
splitters[x].append(y)
53+
54+
def rec(x: int, y: int) -> int:
55+
if (x,y) in found:
56+
return found[(x,y)]
57+
58+
split: int | None = None
59+
if x in splitters and y < max(splitters[x]):
60+
for sy in splitters[x]:
61+
if sy > y:
62+
split = sy
63+
break
64+
65+
if split is None:
66+
return 1
67+
68+
l = rec(x-1, split)
69+
r = rec(x+1, split)
70+
71+
found[(x,y)] = l + r
72+
return l + r
73+
74+
result = rec(i[0].find("S"), 0)
75+
print(f"[P2] Beam was split {result} times")
76+
77+
if __name__ == "__main__":
78+
inputs = _get_input()
79+
if not inputs:
80+
print("Error! Input file is empty!")
81+
sys.exit()
82+
83+
part_1(inputs.copy())
84+
part_2(inputs.copy())
85+
86+
sys.exit()

0 commit comments

Comments
 (0)