Advertisement
Guest User

Advent of Code Day 20

a guest
Dec 27th, 2020
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. """Day 20 of Advent of Code 2020 Solution"""
  2.  
  3. from math import prod
  4. import re
  5.  
  6. from tile import Tile, Image
  7. from tilemakerpro import TileMakerPro
  8.  
  9.  
  10. def data_io(file_location) -> dict[int, Tile]:
  11.     with open(file_location, "r") as f:
  12.         data = f.read().split("\n\n")
  13.         tiles = {}
  14.         for section in data:
  15.             t = section.split("\n")
  16.             id = int(t[0][5:-1])
  17.             tile_map = [[*row] for row in t[1:]]
  18.             tile = Tile(id, tile_map)
  19.             tiles[id] = tile
  20.         return tiles
  21.  
  22.  
  23. def count_monsters(image: Image) -> int:
  24.     l1 = r".{18}#.{1}"
  25.     l2 = r"#.{4}##.{4}##.{4}###"
  26.     l3 = r".{1}#.{2}#.{2}#.{2}#.{2}#.{2}#.{3}"
  27.     n_monsters = 0
  28.     for row in range(len(image) - 3):
  29.         for cols in range(len(image[row]) - 20):
  30.             if all(
  31.                 [
  32.                     re.match(l1, "".join(image[row][cols : cols + 20])),
  33.                     re.match(l2, "".join(image[row + 1][cols : cols + 20])),
  34.                     re.match(l3, "".join(image[row + 2][cols : cols + 20])),
  35.                 ]
  36.             ):
  37.                 n_monsters += 1
  38.     return n_monsters
  39.  
  40.  
  41. def part_a(file_location):
  42.     data = data_io(file_location)
  43.     tmp = TileMakerPro(data)
  44.     return prod(tmp.find_corners())
  45.  
  46.  
  47. def part_b(file_location):
  48.     data = data_io(file_location)
  49.     tmp = TileMakerPro(data)
  50.     tmp.arrange_map()
  51.     t = tmp.consolidate_tiles()
  52.  
  53.     n_rotations = 0
  54.     n_monsters = 0
  55.  
  56.     while n_monsters == 0:
  57.         n_monsters = count_monsters(t.image)
  58.         n_rotations += 1
  59.         t.rotate()
  60.         if n_rotations % 4 == 0:
  61.             t.flip("x")
  62.  
  63.     monster_hash = 15
  64.     map_choppiness = len(["#" for char in t.long_string if char == "#"]) - (
  65.         n_monsters * monster_hash
  66.     )
  67.     return map_choppiness
  68.  
  69.  
  70. if __name__ == "__main__":
  71.     file_location = r"data\day20.txt"
  72.     print(part_a(file_location))
  73.     print(part_b(file_location))
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement