Skip to content

Instantly share code, notes, and snippets.

@p7g
Created December 19, 2020 05:59
Show Gist options
  • Save p7g/570ed0b16176bd8ecfb08eeae70d5dcf to your computer and use it in GitHub Desktop.
Save p7g/570ed0b16176bd8ecfb08eeae70d5dcf to your computer and use it in GitHub Desktop.
data = fetch(19).strip()
rules, messages = map(str.splitlines, data.split("\n\n"))
rs = [None] * len(rules)
for rule in rules:
id_, spec = rule.split(": ")
id_ = int(id_)
if spec[0] == '"':
c = spec[1]
rs[id_] = c
else:
opts = spec.split(" | ")
rs[id_] = [[int(n) for n in opt.split(" ")] for opt in opts]
rules = rs
def do_match(s, rule_id):
rule = rules[rule_id]
if isinstance(rule, str):
if s[0] == rule:
return True, s[1:]
return False, s
for alt in rule:
rem = s
for r in alt:
matched, rem = do_match(rem, r)
if not matched:
break
else:
return True, rem
return False, s
def matches(s, rule_id):
m, rem = do_match(s, rule_id)
return m and not rem
print(sum(matches(msg, 0) for msg in messages))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment