You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 line
1.1KB

  1. import re
  2. import sys
  3. def recurse(rule):
  4. def replacer(m):
  5. return f'({recurse(rules[m.group(1)])})'
  6. return re.sub(r'(\d+)', replacer, rule).replace('"', '').replace(' ', '')
  7. text = sys.stdin.read()
  8. rules, stuff = text.split('\n\n')
  9. rules = dict([ln.split(': ') for ln in rules.splitlines()])
  10. rule0 = re.compile(recurse(rules['0'])).fullmatch
  11. print(sum(bool(rule0(line)) for line in stuff.splitlines()))
  12. def rule8(line):
  13. # 8 = 42 | 42 8
  14. for i in range(1, len(line) + 1):
  15. a, b = line[:i], line[i:]
  16. if rule42(a):
  17. if not b or rule8(b):
  18. return True
  19. def rule11(line):
  20. # 11 = 42 31 | 42 11 31
  21. for i in range(1, len(line) + 1):
  22. for j in range(i, len(line)):
  23. a, b, c = line[:i], line[i:j], line[j:]
  24. if rule42(a) and rule31(c):
  25. if not b or rule11(b):
  26. return True
  27. rule42 = re.compile(recurse(rules['42'])).fullmatch
  28. rule31 = re.compile(recurse(rules['31'])).fullmatch
  29. # 0 = 8 11
  30. ans2 = 0
  31. for ln in stuff.splitlines():
  32. valid = any(rule8(ln[:i]) and rule11(ln[i:]) for i in range(1, len(ln)))
  33. ans2 += bool(valid)
  34. print(ans2)