Skip to content

Commit 6fd2a49

Browse files
committed
Puzzle four - puzzle one and two
1 parent 99ea07a commit 6fd2a49

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

main.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
from utils import load_input_lines, load_input_full
2+
3+
word_search = load_input_lines('04')
4+
5+
NUM_ROWS = len(word_search)
6+
NUM_COLS = len(word_search[0])
7+
8+
9+
def count_target_word_occurances(
10+
word: str,
11+
start_row: int,
12+
start_col: int,
13+
directions: tuple[tuple[int, int]]
14+
) -> int:
15+
16+
occurances = 0
17+
18+
if word_search[start_row][start_col] != word[0]:
19+
return occurances
20+
21+
for dx, dy in directions:
22+
23+
# First, determine whether we can even build a word of sufficient length in
24+
# this given direction.
25+
final_row = start_row + (dx * (len(word) - 1))
26+
final_col = start_col + (dy * (len(word) - 1))
27+
28+
if 0 <= final_row < NUM_ROWS and 0 <= final_col < NUM_COLS:
29+
# We can build a word of sufficient length.
30+
row = start_row
31+
col = start_col
32+
33+
for i in range(len(word) - 1):
34+
row += dx
35+
col += dy
36+
if word_search[row][col] != word[i + 1]:
37+
break
38+
else:
39+
occurances += 1
40+
41+
return occurances
42+
43+
def puzzle_one() -> int:
44+
directions = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1))
45+
count = 0
46+
for row in range(NUM_ROWS):
47+
for col in range(NUM_COLS):
48+
count += count_target_word_occurances('XMAS', row, col, directions)
49+
50+
return count
51+
52+
def puzzle_two() -> int:
53+
directions = {
54+
(1, 1): (-1, -1),
55+
(-1, -1): (1, 1),
56+
(1, -1): (-1, 1),
57+
(-1, 1): (1, -1)
58+
}
59+
60+
count = 0
61+
for row in range(1, NUM_ROWS - 1):
62+
for col in range(1, NUM_COLS - 1):
63+
if word_search[row][col] == 'A':
64+
65+
mas_count = 0
66+
for m, s in directions.items():
67+
m_row, m_col = row + m[0], col + m[1]
68+
s_row, s_col= row + s[0], col + s[1]
69+
if word_search[m_row][m_col] == 'M' and word_search[s_row][s_col] == 'S':
70+
mas_count += 1
71+
72+
if mas_count > 1:
73+
count += 1
74+
75+
return count
76+
77+
if __name__ == "__main__":
78+
print(puzzle_one())
79+
print(puzzle_two())

template.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from utils import load_input_lines, load_input_full
2+
3+
input = load_input_full()
4+
5+
6+
def puzzle_one() -> int:
7+
...
8+
9+
def puzzle_two() -> int:
10+
...
11+
12+
13+
if __name__ == "__main__":
14+
print(puzzle_one())
15+
print(puzzle_two())

0 commit comments

Comments
 (0)