Advertisement
hugseverycat

AoC Day 19

Dec 19th, 2020 (edited)
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. import re
  2.  
  3. input_list = []
  4. input_filename = "day19.txt"
  5. # input_filename = "sample_input.txt"
  6. part2 = True
  7.  
  8. switch = False
  9. rules = {}
  10. messages = []
  11.  
  12. with open(input_filename, 'r') as reader:
  13.     for line in reader:
  14.         if line == '\n':
  15.             switch = True
  16.         if not switch:
  17.             temp_line = (str(line.rstrip())).replace('"', '').split(' ')
  18.             rules[temp_line[0][:-1]] = temp_line[1:]
  19.         else:
  20.             messages.append(str(line.rstrip()))
  21.  
  22.  
  23. def build_regex(r: str):
  24.     global rules
  25.  
  26.     if rules[r][0] in "ab":
  27.         return rules[r][0]
  28.     rx = "("
  29.     for this_rule in rules[r]:
  30.         if this_rule == "|":
  31.             rx += this_rule
  32.         else:
  33.             rx += build_regex(this_rule)
  34.     rx += ")"
  35.     return rx
  36.  
  37.  
  38. my_regex = f"^{build_regex('0')}$"
  39. counter_p1 = 0
  40. for this_message in messages:
  41.     if re.match(my_regex, this_message):
  42.         counter_p1 += 1
  43.  
  44. rule42 = build_regex("42")
  45. rule31 = build_regex("31")
  46.  
  47. counter_p2 = 0
  48.  
  49. for n in range(1, 5):  # 5 was determined by trial-and-error; any lower and we start losing matches.
  50.     my_regex = f"^({rule42}+{rule42}{{{n}}}{rule31}{{{n}}})$"
  51.     for this_message in messages:
  52.         if re.match(my_regex, this_message):
  53.             counter_p2 += 1
  54.  
  55. print(f"Part 1: {counter_p1}")
  56. print(f"Part 2: {counter_p2}")
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement