Skip to content

Commit 9221749

Browse files
committed
Day 4! Needed numpy help for 04a but 04b was MUCH easier
1 parent a3bfbfd commit 9221749

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

04/04a.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import numpy as np
2+
import re
3+
4+
with open('input', 'r') as f: source = f.read().split('\n')
5+
6+
matrix = []
7+
8+
for y in source:
9+
row = []
10+
for x in range(len(y)):
11+
row.append(y[x])
12+
matrix.append(row)
13+
14+
print(matrix)
15+
16+
npm = np.matrix(matrix)
17+
print(npm)
18+
19+
# No way I could've done this without numpy and this answer: https://stackoverflow.com/a/6313414
20+
npdiags = [npm[::-1,:].diagonal(i) for i in range(-npm.shape[0]+1,npm.shape[1])]
21+
npdiags.extend(npm.diagonal(i) for i in range(npm.shape[1]-1,-npm.shape[0],-1))
22+
diags = [ i.tolist() for i in npdiags ]
23+
24+
print(diags)
25+
26+
total = 0
27+
28+
# Search rows
29+
for y in matrix:
30+
row = ''.join(y)
31+
# This total adding thing shoulda been a function
32+
total += len(re.findall(r'XMAS', row))
33+
total += len(re.findall(r'XMAS', row[::-1]))
34+
35+
print(f'{total=}')
36+
37+
# Search columns
38+
for x in range(len(matrix[0])):
39+
column = ''.join(npm[:, x].flatten().tolist()[0])
40+
total += len(re.findall(r'XMAS', column))
41+
total += len(re.findall(r'XMAS', column[::-1]))
42+
43+
print(f'{total=}')
44+
45+
# Search diagonals
46+
for d in diags:
47+
diag = ''.join(d[0])
48+
total += len(re.findall(r'XMAS', diag))
49+
total += len(re.findall(r'XMAS', diag[::-1]))
50+
51+
print(f'{total=}')

04/04b.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
with open('input', 'r') as f: source = f.read().split('\n')
2+
3+
matrix = []
4+
5+
for y in source:
6+
row = []
7+
for x in range(len(y)):
8+
row.append(y[x])
9+
matrix.append(row)
10+
11+
print(matrix)
12+
13+
count = 0
14+
15+
# M A S is 3 long so
16+
for y in range(len(matrix) - 2):
17+
for x in range(len(matrix[x]) - 2):
18+
print(f'{x},{y} = {matrix[y][x]}')
19+
20+
tl = matrix[y][x]
21+
tr = matrix[y][x+2]
22+
mi = matrix[y+1][x+1]
23+
bl = matrix[y+2][x]
24+
br = matrix[y+2][x+2]
25+
26+
if (tl == "M" and br == "S") or (tl == "S" and br == "M"):
27+
if (tr == "S" and bl == "M") or (tr == "M" and bl == "S"):
28+
if (mi == "A"):
29+
count += 1
30+
31+
print(f'{count=}')

0 commit comments

Comments
 (0)