Skip to content

Commit 56e53d4

Browse files
committed
Completed part 1 of day 20 of year 2024
1 parent a8c309c commit 56e53d4

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

2024/20.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
def parse(data):
5+
grid = []
6+
boundX, boundY = len(data.split('\n')[0]), len(data.split('\n'))
7+
start = None, None
8+
end = None, None
9+
for y, line in enumerate(data.split('\n')):
10+
for x, char in enumerate(line):
11+
if char == '#':
12+
grid.append((x, y))
13+
elif char == '.':
14+
pass
15+
elif char == 'S':
16+
start = x, y
17+
elif char == 'E':
18+
end = x, y
19+
20+
return grid, (boundX, boundY), start, end
21+
22+
split_data = parse
23+
completed = 1
24+
raw_data = None # Not To be touched
25+
26+
def pathFinder(grid, start, end):
27+
# Simple greedy algo since there is only one path
28+
path = [start, start]
29+
directions = [(0, -1), (0, 1), (1, 0), (-1, 0)]
30+
while path[-1] != end:
31+
# print(path[-1])
32+
for dx, dy in directions:
33+
nx, ny = path[-1][0]+dx, path[-1][1]+dy
34+
if (nx, ny) in grid: continue
35+
if (nx, ny) == path[-2]: continue
36+
37+
path.append((nx, ny))
38+
break
39+
40+
return path[1:]
41+
42+
43+
def part1(data):
44+
grid, bounds, start, end = data
45+
path = pathFinder(grid, start, end)
46+
47+
moves = [(0, -2), (0, 2), (2, 0), (-2, 0)]
48+
49+
counter = 0
50+
51+
for i, (x, y) in enumerate(path):
52+
for dx, dy in moves:
53+
nx, ny = x + dx, y + dy
54+
if (nx, ny) not in path[i:]: continue
55+
save = path[i:].index((nx, ny)) - 2
56+
if save >= 100: counter += 1
57+
58+
return counter
59+
60+
def part2(data):
61+
grid, bounds, start, end = data
62+
path = pathFinder(grid, start, end)
63+
64+
# Some black magic is required over here cause the amount of checks look like 10k * 50**2 ~= 25 mill
65+
moves = [(0, -2), (0, 2), (2, 0), (-2, 0)]
66+
67+
counter = 0
68+
69+
for i, (x, y) in enumerate(path):
70+
for dx, dy in moves:
71+
nx, ny = x + dx, y + dy
72+
if (nx, ny) not in path[i:]: continue
73+
save = path[i:].index((nx, ny)) - 2
74+
if save >= 100: counter += 1
75+
76+
return counter

0 commit comments

Comments
 (0)