-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday4.py
More file actions
executable file
·58 lines (41 loc) · 1.4 KB
/
Copy pathday4.py
File metadata and controls
executable file
·58 lines (41 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from itertools import islice, combinations
from aoc_utils import * # type: ignore
from aocd import get_data
data = get_data(year=2024, day=4, block=True)
def word_search(grid, word):
taken = set()
reverse = "".join(reversed(word))
ray_length = len(word) - 1
for yx, c in grid.row_major_with_index():
for d in [Direction.EAST, Direction.SE, Direction.SOUTH, Direction.SW]:
ray = islice(grid.ray_from_with_index(yx, d), ray_length)
chars = [c]
pos = [yx]
for yyx, cc in ray:
pos.append(yyx)
chars.append(cc)
string = "".join(chars)
if string == word or string == reverse:
taken.add(tuple(sorted(pos)))
return taken
def part_one(data):
grid = Grid([[c for c in line] for line in data.splitlines()])
return len(word_search(grid, "XMAS"))
def part_two(data):
grid = Grid([[c for c in line] for line in data.splitlines()])
occurances = word_search(grid, "MAS")
xmases = 0
for first, second in combinations(occurances, 2):
m1, a1, s1 = first
m2, a2, s2 = second
if (
m1[0] == m2[0]
and abs(m1[1] - m2[1]) == 2
and a1 == a2
and s1[0] == s2[0]
and abs(s1[1] - s2[1]) == 2
):
xmases += 1
return xmases
print(part_one(data))
print(part_two(data))