Skip to content

Instantly share code, notes, and snippets.

@rainey
Created December 5, 2024 15:20
Show Gist options
  • Select an option

  • Save rainey/648b82660c37ff278b62f2663d68cd6d to your computer and use it in GitHub Desktop.

Select an option

Save rainey/648b82660c37ff278b62f2663d68cd6d to your computer and use it in GitHub Desktop.
import sys
import numpy as np
import time
import scipy.ndimage as ndimage
searchlines = []
with open(sys.argv[1], "r") as f_in:
searchlines = [[ord(c) for c in line.strip()] for line in f_in]
srch_matrix = np.array(searchlines, dtype='u8')
def count_xmas(arr: np.array, deg=0):
arr = np.rot90(arr, k=deg/90)
# arr = np.rot90(arr, angle=deg, order=0, prefilter=False, axes=[1,0])
needle = np.array([ord(c) for c in "XMAS"], dtype="u8")
conv_arr = [4,3,2,1]
convsum = np.convolve(needle, conv_arr)[3]
conv = np.array([np.convolve(l, conv_arr) for l in arr])
xmas_diag = np.array([[ord("X"), 0,0,0], [0, ord("M"), 0,0], [0,0, ord("A"),0], [0,0,0,ord("S")]])
diag_conv_m = np.array([[1, 0 , 0, 0], [0, 11, 0,0], [0, 0, 101,0], [0,0,0,1003]])
diag_conv = ndimage.convolve(xmas_diag, diag_conv_m, mode="constant")
print(diag_conv)
def diagonal(m, n):
return np.array([arr[m+i, n+i] for i in range(min(arr.shape[0]-m, arr.shape[1]-n))])
def print_as_char(arr):
print("\n".join(["".join([chr(i) if i else ' ' for i in r]) for r in arr]))
diagonals = [diagonal(0, j) for j in range(arr.shape[1])] + [diagonal(i, 0) for i in range(1, arr.shape[0])]
diagonal_convs = [np.convolve(d, conv_arr) for d in diagonals]
arr_diag_conv = ndimage.convolve(arr, diag_conv, mode="constant")
print(arr_diag_conv)
# print_as_char(diagonals)
d_xmas = sum(np.count_nonzero(c == convsum) for c in diagonal_convs)
# d_xmas = np.count_nonzero(arr_diag_conv == diag_conv_m[1,1])
# print(f"Rotation {deg}")
# print_as_char(arr)
# print("------")
return np.count_nonzero(conv == convsum) + d_xmas #+ np.count_nonzero(diagonal_convs == convsum)
def count_x_mas(arr, deg=0):
arr = np.rot90(arr, k=deg/90)
x_mas = [['M', '\0', 'M'], ['\0', 'A', '\0'], ['S', '\0', 'S']]
xmask = np.array([[ord(i) for i in j] for j in x_mas])
conv_matrix = np.array([[1, 0 ,3], [0, 11, 0], [100, 0, 101]])
conv_match = ndimage.convolve(xmask, conv_matrix, mode='constant')[1,1]
conv_res = ndimage.convolve(arr, conv_matrix, mode='constant')
# print(conv_res)
return np.count_nonzero(conv_res == conv_match)
# Correct answers with day4.in, md54sum 5fcbd00d8ba246818c056d95ab2b5060:
#2336
#1831
start = time.time()
print(sum([count_xmas(srch_matrix, deg=d) for d in [0, 90, 180, 270]]))
c1 = time.time()
print(sum([count_x_mas(srch_matrix, deg=d) for d in [0, 90, 180, 270]]))
c2 = time.time()
print(f"p1: {c1-start}, p2: {c2-c1}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment