Skip to content

Instantly share code, notes, and snippets.

@aledesole
Last active December 16, 2020 14:56
Show Gist options
  • Save aledesole/421ca948226d81837899ec96fb1ed3e7 to your computer and use it in GitHub Desktop.
Save aledesole/421ca948226d81837899ec96fb1ed3e7 to your computer and use it in GitHub Desktop.
Advent of code 2020, Day 16, Python3.9
from sys import stdin
from re import findall
from collections import defaultdict
from functools import reduce
import operator
parts = [[findall('\d+', l)
for l in x.split('\n')]
for x in stdin.read().split('\n\n')]
rules = [[[int(r[i]),int(r[i+1])]
for i in range(0,len(r),2)]
for r in parts[0]]
ticket = [int(n) for n in parts[1][1]]
nearby = [[int(n) for n in t] for t in parts[2][1:] if t]
# Part 1
bad = [
x for x in (int(n) for t in nearby for n in t)
if not any(r[0]<=x<=r[1]
for r in (r for sr in rules for r in sr))]
print (sum(bad))
# Part 2
matches = defaultdict(list)
for i,col in enumerate(zip(*(t for t in nearby
if all(x not in bad for x in t)))):
for j,rule in enumerate(rules):
if all(any(r[0]<=x<=r[1] for r in rule) for x in col):
matches[j].append(i)
mapping = {}
for i in sorted(matches, key=lambda x: len(matches[x])):
mapping[next(x for x in matches[i] if x not in mapping)] = i
print(reduce(operator.mul,
(ticket[i] for i,j in mapping.items() if j<6), 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment