usesbiggerwords

AoC 2021 Day 10

Dec 10th, 2021
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. import os
  2. from copy import deepcopy
  3.  
  4. CLOSE_CHARS = '}]>)'
  5.  
  6. def read_and_init(fn):
  7.     with open(fn, 'r') as f:
  8.         return f.read().splitlines()
  9.  
  10.  
  11. def scan(chunk) -> int:
  12.     depth = []
  13.     mates = {'}': '{', ']': '[', '>': '<', ')': '('}
  14.     scoring = {')': 3, ']': 57, '}': 1197, '>': 25137}
  15.     p = 0
  16.     while p < len(chunk):
  17.         if chunk[p] in CLOSE_CHARS:
  18.             if depth[-1] != mates[chunk[p]]:
  19.                 return scoring[chunk[p]]
  20.             else:
  21.                 depth.pop()
  22.         else:
  23.             depth.append(chunk[p])
  24.         p += 1
  25.     return 0
  26.  
  27.  
  28. def autocomplete(chunks):
  29.     scores = []
  30.     mates = {'(': ')', '[': ']', '{': '}', '<': '>'}
  31.     scoring = {')': 1, ']': 2, '}': 3, '>': 4}
  32.     for chunk in chunks:
  33.         p = 0
  34.         score = 0
  35.         depth = []
  36.         while p < len(chunk):
  37.             if chunk[p] in CLOSE_CHARS:
  38.                 depth.pop()
  39.             else:
  40.                 depth.append(chunk[p])
  41.             p += 1
  42.         depth = list(reversed([mates[d] for d in depth]))
  43.         for char in depth:
  44.             score = score * 5 + scoring[char]
  45.         scores.append(score)
  46.     scores.sort()
  47.     return scores[len(scores) // 2]
  48.  
  49.  
  50. def part1(chunks: list):
  51.     score = 0
  52.     for chunk in chunks:
  53.         score += scan(chunk)
  54.     return score
  55.  
  56.  
  57. def part2(chunks: list):
  58.     chunks_copy = deepcopy(chunks)
  59.     p = 0
  60.     while p < len(chunks):
  61.         if scan(chunks[p]) > 0:
  62.             chunks_copy.remove(chunks[p])
  63.         p += 1
  64.     score = autocomplete(chunks_copy[:])
  65.     return score
  66.  
  67.  
  68. c = read_and_init(os.path.dirname(__file__) + '\\in.txt')
  69. res1 = part1(c)
  70. print('Part 1:', res1)
  71. res2 = part2(c)
  72. print('Part 2:', res2)
Advertisement
Add Comment
Please, Sign In to add comment