Skip to content

Commit a614b04

Browse files
committed
Day 6 Part 2 Slow
1 parent c6707f6 commit a614b04

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

2024/day_06/Python/guards.py

+29-9
Original file line numberDiff line numberDiff line change
@@ -33,28 +33,48 @@ def out_of_bounds(area, cursor) -> bool:
3333
)
3434

3535

36-
def count_paces(area_str: str) -> int:
37-
area_list_of_lists = [list(line) for line in area_str.splitlines()[1:]]
38-
area = np.array(area_list_of_lists)
39-
area = np.pad(area,1, "constant",constant_values='_')
40-
41-
(cursor,) = np.argwhere(area == "^")
36+
def has_loop(area) -> int:
4237
direction = np.array([-1, 0])
4338

4439
total_visited = 0
4540
newly_visited = True
41+
visited_set = set()
42+
(cursor,) = np.argwhere(area == "^")
43+
4644

47-
while not area[tuple(cursor)] == "_":
45+
46+
while not (area[tuple(cursor)] == "_" or (tuple(cursor),tuple(direction)) in visited_set):
47+
visited_set.add((tuple(cursor),tuple(direction)))
4848
total_visited += newly_visited
4949
cursor, direction, newly_visited = walk(area, cursor, direction)
5050

51-
return total_visited
51+
return (tuple(cursor),tuple(direction)) in visited_set
52+
53+
def iterate_obstacles(area_str: str):
54+
area_list_of_lists = [list(line) for line in area_str.splitlines()[1:]]
55+
area = np.array(area_list_of_lists)
56+
area_padded = np.pad(area,1, "constant",constant_values='_')
57+
loops = 0
58+
59+
for x_pos in range(1, area_padded.shape[0]-1):
60+
for y_pos in range(1, area_padded.shape[1]-1):
61+
area_copy = area_padded.copy()
62+
# print(x_pos, y_pos)
63+
if area_padded[(x_pos, y_pos)] == "^":
64+
print("HELP ME")
65+
else:
66+
area_copy[(x_pos,y_pos)] = "#"
67+
if has_loop(area_copy):
68+
loops+=1
69+
print(x_pos)
70+
71+
return loops
5272

5373

5474
def main():
5575
with open("input","r") as f:
5676
data = f.read()
57-
print(count_paces(data))
77+
print(iterate_obstacles(data))
5878

5979

6080
if __name__ == "__main__":

2024/day_06/Python/test_guards.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
from guards import count_paces
2-
1+
from guards import iterate_obstacles
32

43
INPUT = """
54
....#.....
@@ -16,4 +15,4 @@
1615

1716

1817
def test_guards():
19-
assert count_paces(INPUT) == 41
18+
assert iterate_obstacles(INPUT) == 6

0 commit comments

Comments
 (0)