Guest User

AoC iv2b day 4 2024

a guest
Dec 5th, 2024
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. def FindPattern(matrix, pattern, coord, step):
  2.     maxY = len(matrix)-1
  3.     maxX = len(matrix[0])-1
  4.  
  5.     for p in list(pattern):
  6.         if coord[0] < 0 or coord[0] > maxY:
  7.             return False
  8.         if coord[1] < 0 or coord[1] > maxX:
  9.             return False
  10.         if p != matrix[coord[0]][coord[1]]:
  11.             return False
  12.  
  13.         coord[0] += step[0]
  14.         coord[1] += step[1]
  15.  
  16.     return True
  17.  
  18.  
  19. file = open('input.txt', mode = 'r', encoding = 'utf-8-sig')
  20. lines = file.read().splitlines()
  21. file.close()
  22.  
  23. matrix = []
  24.  
  25. for i, line in enumerate(lines):
  26.     matrix.append(list(line))
  27.  
  28. occurrences = 0
  29.  
  30. # part 1
  31. for y, row in enumerate(matrix):
  32.     for x, col in enumerate(row):
  33.         # go right
  34.         if FindPattern(matrix, "XMAS", [y,x], (0,1)):
  35.             occurrences += 1
  36.         # go left
  37.         if FindPattern(matrix, "XMAS", [y,x], (0,-1)):
  38.             occurrences += 1
  39.         # go up
  40.         if FindPattern(matrix, "XMAS", [y,x], (-1,0)):
  41.             occurrences += 1
  42.         # go down
  43.         if FindPattern(matrix, "XMAS", [y,x], (1,0)):
  44.             occurrences += 1
  45.  
  46.         # go up right
  47.         if FindPattern(matrix, "XMAS", [y,x], (-1,1)):
  48.             occurrences += 1
  49.         # go up left
  50.         if FindPattern(matrix, "XMAS", [y,x], (-1,-1)):
  51.             occurrences += 1
  52.         # go down right
  53.         if FindPattern(matrix, "XMAS", [y,x], (1,1)):
  54.             occurrences += 1
  55.         # go down left
  56.         if FindPattern(matrix, "XMAS", [y,x], (1,-1)):
  57.             occurrences += 1
  58.  
  59. print(occurrences)
  60.  
  61. #part 2
  62. occurrences = 0
  63.  
  64. for y, row in enumerate(matrix):
  65.     for x, col in enumerate(row):
  66.         # check both diagonals
  67.         if FindPattern(matrix, "MAS", [y,x], (1,1)) or FindPattern(matrix, "SAM", [y,x], (1,1)):
  68.             if FindPattern(matrix, "MAS", [y+2,x], (-1,1)) or FindPattern(matrix, "SAM", [y+2,x], (-1,1)):
  69.                 occurrences += 1
  70.  
  71.  
  72. print(occurrences)
Advertisement
Add Comment
Please, Sign In to add comment