Advertisement
Guest User

Untitled

a guest
Dec 5th, 2024
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. def parse_input(filename=0):
  2.     with open(filename) as f:
  3.         lines = [l.strip() for l in f.readlines()]
  4.     return lines
  5.  
  6. def p1(lines):
  7.     c = 0
  8.     for row, line in enumerate(lines):
  9.         # Straight left-right
  10.         s = line
  11.         c += s.count('XMAS') + s.count('SAMX')
  12.         # Half of diagonals going down right
  13.         s = ''.join(
  14.             lines[y][x] for x, y in zip(
  15.                 range(len(line)),
  16.                 range(row, len(lines))
  17.             )
  18.         )
  19.         c += s.count('XMAS') + s.count('SAMX')
  20.         # Half of diagonals going up right
  21.         s = ''.join(
  22.             lines[y][x] for x, y in zip(
  23.                 range(row, -1, -1),
  24.                 range(len(lines[0]))
  25.             )
  26.         )
  27.         c += s.count('XMAS') + s.count('SAMX')
  28.  
  29.     for col in range(len(lines[0])):
  30.         # Straight up-down
  31.         s = ''.join(l[col] for l in lines)
  32.         c += s.count('XMAS') + s.count('SAMX')
  33.         # So we don't double dip the diagonals
  34.         if col > 0:
  35.             # Other half of diagonals down-right
  36.             s = ''.join(
  37.                 lines[y][x] for x, y in zip(
  38.                 range(col, len(lines[0])),
  39.                 range(len(lines))
  40.                 )
  41.             )
  42.             c += s.count('XMAS') + s.count('SAMX')
  43.             # Other half of diagonals up-right
  44.             s = ''.join(
  45.             lines[y][x] for x, y in zip(
  46.                 range(len(lines) - 1, -1, -1),
  47.                 range(col, len(lines[0]))
  48.                 )
  49.             )
  50.             c += s.count('XMAS') + s.count('SAMX')
  51.  
  52.     print(c)
  53.  
  54. def p2(lines):
  55.     # Both diagonals around 'A' should have the characters 'A', 'M', and 'S',
  56.     # sorted alphabetically
  57.     key = ['A', 'M', 'S']
  58.     c = 0
  59.     for y in range(1, len(lines) - 1):
  60.         for x in range(1, len(lines[0]) - 1):
  61.             if lines[y][x] == 'A':
  62.                 s1 = sorted(lines[y + i][x + i] for i in range(-1, 2))
  63.                 s2 = sorted(lines[y - i][x + i] for i in range(-1, 2))
  64.                 if s1 == key and s2 == key:
  65.                     c += 1
  66.     print(c)
  67.  
  68. puzzle_input = parse_input()
  69.  
  70. p1(puzzle_input[:])
  71. p2(puzzle_input[:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement