aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

2.py (944B) [raw]


      1 #!/usr/bin/env python3
      2 import sys
      3 
      4 G = []
      5 
      6 # Safely get an item from the grid without out-of-bounds errs
      7 def get(i, j):
      8     if i >= 0 and i < len(G) and j >= 0 and j < len(G[0]):
      9         return G[i][j]
     10     return ""
     11 
     12 # Trick: rather than start the search on a M, which involves
     13 # making sure that there's a diagonal MAS counterpart
     14 # (which also involves avoiding double counting), just look
     15 # for the A in the middle thats shared!
     16 def xmas(i, j):
     17     if G[i][j] != "A":
     18         return 0
     19 
     20     return (
     21         (get(i+1, j+1) == "S" and get(i-1, j-1) == "M") or
     22         (get(i+1, j+1) == "M" and get(i-1, j-1) == "S")
     23         ) and (
     24         (get(i-1, j+1) == "S" and get(i+1, j-1) == "M") or
     25         (get(i-1, j+1) == "M" and get(i+1, j-1) == "S")
     26     )
     27 
     28 # Read the puzzle
     29 for l in sys.stdin:
     30     letts = [c for c in l.strip()]
     31     G.append(letts)
     32 
     33 c = 0
     34 for i in range(len(G)):
     35     for j in range(len(G[0])):
     36         c += xmas(i, j)
     37 
     38 print(c)