Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Day 20 of Advent of Code 2020 Solution"""
- from math import prod
- import re
- from tile import Tile, Image
- from tilemakerpro import TileMakerPro
- def data_io(file_location) -> dict[int, Tile]:
- with open(file_location, "r") as f:
- data = f.read().split("\n\n")
- tiles = {}
- for section in data:
- t = section.split("\n")
- id = int(t[0][5:-1])
- tile_map = [[*row] for row in t[1:]]
- tile = Tile(id, tile_map)
- tiles[id] = tile
- return tiles
- def count_monsters(image: Image) -> int:
- l1 = r".{18}#.{1}"
- l2 = r"#.{4}##.{4}##.{4}###"
- l3 = r".{1}#.{2}#.{2}#.{2}#.{2}#.{2}#.{3}"
- n_monsters = 0
- for row in range(len(image) - 3):
- for cols in range(len(image[row]) - 20):
- if all(
- [
- re.match(l1, "".join(image[row][cols : cols + 20])),
- re.match(l2, "".join(image[row + 1][cols : cols + 20])),
- re.match(l3, "".join(image[row + 2][cols : cols + 20])),
- ]
- ):
- n_monsters += 1
- return n_monsters
- def part_a(file_location):
- data = data_io(file_location)
- tmp = TileMakerPro(data)
- return prod(tmp.find_corners())
- def part_b(file_location):
- data = data_io(file_location)
- tmp = TileMakerPro(data)
- tmp.arrange_map()
- t = tmp.consolidate_tiles()
- n_rotations = 0
- n_monsters = 0
- while n_monsters == 0:
- n_monsters = count_monsters(t.image)
- n_rotations += 1
- t.rotate()
- if n_rotations % 4 == 0:
- t.flip("x")
- monster_hash = 15
- map_choppiness = len(["#" for char in t.long_string if char == "#"]) - (
- n_monsters * monster_hash
- )
- return map_choppiness
- if __name__ == "__main__":
- file_location = r"data\day20.txt"
- print(part_a(file_location))
- print(part_b(file_location))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement