2020 day 19 and day 20 part 1
This commit is contained in:
62
2020/d19.py
Normal file
62
2020/d19.py
Normal file
@@ -0,0 +1,62 @@
|
||||
from lib import get_data
|
||||
|
||||
data = get_data(__file__)
|
||||
|
||||
rules = {}
|
||||
msgs = []
|
||||
|
||||
for line in data.splitlines():
|
||||
if len(line.strip()) == 0:
|
||||
continue
|
||||
|
||||
if ":" in line:
|
||||
id, rule = line.split(":")
|
||||
id = int(id)
|
||||
|
||||
branches = [[]]
|
||||
for part in rule.split():
|
||||
if part.startswith('"') and part.endswith('"'):
|
||||
branches = part[1]
|
||||
elif part == "|":
|
||||
assert type(branches) is list
|
||||
branches.append([])
|
||||
else:
|
||||
assert type(branches) is list
|
||||
branches[-1].append(int(part))
|
||||
rules[id] = branches
|
||||
else:
|
||||
msgs.append(line.strip())
|
||||
|
||||
|
||||
def matches(xs, rule):
|
||||
if xs == "" and rule == []:
|
||||
return True
|
||||
elif xs == "" or rule == []:
|
||||
return False
|
||||
|
||||
current = rules[rule[0]]
|
||||
if current == xs[0]:
|
||||
return matches(xs[1:], rule[1:])
|
||||
elif type(current) is str:
|
||||
return False
|
||||
elif len(current) >= 1:
|
||||
for ys in current:
|
||||
if matches(xs, ys + rule[1:]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
t = 0
|
||||
for m in msgs:
|
||||
if matches(m, rules[0][0]):
|
||||
t += 1
|
||||
print(t)
|
||||
|
||||
rules[8] = [[42], [42, 8]]
|
||||
rules[11] = [[42, 31], [42, 11, 31]]
|
||||
|
||||
t = 0
|
||||
for m in msgs:
|
||||
if matches(m, rules[0][0]):
|
||||
t += 1
|
||||
print(t)
|
||||
Reference in New Issue
Block a user