Skip to content

Commit e611567

Browse files
committed
2024, day 6,day 1 (incorrect)
1 parent ac21ce5 commit e611567

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

2024/day06.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
from collections import namedtuple
2+
3+
# Taken from Norvig
4+
# https://github.com/norvig/pytudes/blob/main/ipynb/Advent-2017.ipynb
5+
6+
# (x, y-1)
7+
# (x-1, y) (x, y ) (x+1, y)
8+
# (x, y+1)
9+
10+
HEADINGS = UP, LEFT, DOWN, RIGHT = (0, -1), (-1, 0), (0, 1), (1, 0)
11+
12+
13+
def turn_right(heading):
14+
return HEADINGS[HEADINGS.index(heading) - 1]
15+
16+
17+
Grid = namedtuple("Grid", ["current", "heading", "obstacles", "visited"])
18+
19+
20+
def parse(lines):
21+
current = next(
22+
(x, y)
23+
for y, row in enumerate(lines)
24+
for x, content in enumerate(row)
25+
if content == "^"
26+
)
27+
heading = UP
28+
obstacles = [
29+
(x, y)
30+
for y, row in enumerate(lines)
31+
for x, content in enumerate(row)
32+
if content == "#"
33+
]
34+
visited = 0
35+
return Grid(current, heading, obstacles, visited)
36+
37+
38+
def next_step(current, heading):
39+
return tuple(c + h for c, h in zip(current, heading))
40+
41+
42+
def visualize(obstacles, nxt, heading):
43+
arrows = "^<v>"
44+
rows = []
45+
for y in range(11):
46+
row = []
47+
for x in range(11):
48+
if (x, y) == nxt:
49+
row.append(arrows[HEADINGS.index(heading)])
50+
else:
51+
row.append("#" if (x, y) in obstacles else ".")
52+
rows.append("".join(row))
53+
print("\n".join(rows))
54+
55+
56+
def walk(grid):
57+
"""Walk one step and simulate the new state of the grid"""
58+
current, heading, obstacles, visited = grid
59+
if next_step(current, heading) in obstacles:
60+
print("turning")
61+
heading = turn_right(heading)
62+
nxt = next_step(current, heading)
63+
visited += 1
64+
print(nxt, heading, visited)
65+
visualize(obstacles, nxt, heading)
66+
print()
67+
return Grid(nxt, heading, obstacles, visited)
68+
69+
70+
if __name__ == "__main__":
71+
map = """
72+
....#.....
73+
.........#
74+
..........
75+
..#.......
76+
.......#..
77+
..........
78+
.#..^.....
79+
........#.
80+
#.........
81+
......#..."""
82+
83+
# repeat(50, walk, parse(map))
84+
lines = [list(line) for line in map.strip().splitlines()]
85+
max_y = len(lines)
86+
max_x = len(lines[0])
87+
grid = parse(lines)
88+
walking = True
89+
while walking:
90+
grid = walk(grid)
91+
if not (0 <= grid.current[0] <= max_x) or not (0 <= grid.current[1] <= max_y):
92+
walking = False
93+
print(grid.visited)

0 commit comments

Comments
 (0)