My solutions for Advent of Code.
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.
adventofcode/2020/19.py

99 lines
2.0 KiB

4 years ago
#!/usr/bin/env python
from aoc import get_input # AoC
import re
4 years ago
from functools import lru_cache
4 years ago
from copy import deepcopy as copy
4 years ago
data = get_input(19)
rules = data.split("\n\n")[0].split("\n")
messages = data.split("\n\n")[1].split("\n")
rulePrim = dict()
for i, rule in enumerate(rules): # make a dict for the rules
index, val = re.split(r": ", rule)
rulePrim[int(index)] = val.replace('"', "")
4 years ago
@lru_cache
def containsPointers(ruleStr): # function to check if a rule contains a pointer
return any(char.isnumeric() for char in ruleStr)
@lru_cache
def getPointersAtPos(string, starti=0):
thing = set(re.findall( r"\d+", string[starti:] ))
4 years ago
4 years ago
return thing
4 years ago
4 years ago
from sys import setrecursionlimit
setrecursionlimit(20000)
4 years ago
4 years ago
@lru_cache
4 years ago
def genRegex(rule, loop=False, i=0):
4 years ago
cont = rulePrim[rule]
cont = cont.split(" ")
4 years ago
4 years ago
reg = "("
for char in cont:
ispointer = char.isnumeric()
if( ispointer ):
4 years ago
if( i < 498 ):
reg += genRegex(int(char), loop, i+1)
else:
reg += "(\w+)"
4 years ago
else:
reg += char
reg += ")"
4 years ago
4 years ago
return reg
4 years ago
4 years ago
def removeSpaces(rule):
# remove spaces because they are evil
cont = rulePrim[rule]
rulePrim[rule] = cont.replace(" ", "")
rulePrim[rule] = "^" + rulePrim[rule] + "$"
4 years ago
4 years ago
return rulePrim[rule]
4 years ago
4 years ago
# go through all messages and check
def part1(rulePrim, messages):
count = 0
mesLen = len(messages)
for i, message in enumerate(messages):
check = re.match(rulePrim[0], message)
if(check):
count += 1
4 years ago
print(message)
4 years ago
4 years ago
print("Part1:", count)
4 years ago
4 years ago
4 years ago
rulePrim[8] = "42 | 42 8"
rulePrim[11] = "42 31 | 42 11 31"
4 years ago
4 years ago
rulePrim[8] = genRegex(8)
rulePrim[11] = genRegex(11)
# rulePrim[0] = genRegex(0)
# rulePrim[0] = removeSpaces(0)
# part1(rulePrim, messages)
# rulePrim[8] = "42 | 42 ([a-b]+)"
# rulePrim[11] = "42 31 | 42 ([a-b]+) 31"
rulePrim[0] = genRegex(0)
print("reg done")
4 years ago
rulePrim[0] = removeSpaces(0)
part1(rulePrim, messages)