added rest of the code
This commit is contained in:
53
19/part1.py
Normal file
53
19/part1.py
Normal file
@ -0,0 +1,53 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
import re
|
||||
|
||||
RE_RULE = re.compile(r'^(.*) => (.*)$')
|
||||
|
||||
|
||||
def read_file(filename):
|
||||
file = open(filename, 'r')
|
||||
while True:
|
||||
line = file.readline()
|
||||
if not line:
|
||||
break
|
||||
yield line.strip()
|
||||
|
||||
|
||||
def apply_rule(formula, key, value):
|
||||
keyLen = len(key)
|
||||
formulaPos = 0
|
||||
|
||||
# print "formula: %s, key: %s, value: %s" % (formula, key, value)
|
||||
while True:
|
||||
pos = formula.find(key, formulaPos)
|
||||
# print " - pos: %d" % (pos)
|
||||
if pos < 0:
|
||||
break
|
||||
yield formula[0:pos] + value + formula[pos+keyLen:]
|
||||
formulaPos = pos + keyLen
|
||||
|
||||
|
||||
def main():
|
||||
formula = ""
|
||||
rules = dict()
|
||||
for line in read_file('input'):
|
||||
# skip empty lines
|
||||
if not line:
|
||||
continue
|
||||
match = re.match(RE_RULE, line)
|
||||
if match:
|
||||
if match.group(1) not in rules:
|
||||
rules[match.group(1)] = []
|
||||
rules[match.group(1)].append(match.group(2))
|
||||
else:
|
||||
formula = line
|
||||
|
||||
for k1, v1 in rules.iteritems():
|
||||
for v2 in v1:
|
||||
for r in apply_rule(formula, k1, v2):
|
||||
print r
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
55
19/part2.py
Normal file
55
19/part2.py
Normal file
@ -0,0 +1,55 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# solution borrowd from
|
||||
# https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/?sort=new
|
||||
|
||||
import re
|
||||
from random import shuffle
|
||||
|
||||
RE_RULE = re.compile(r'^(.*) => (.*)$')
|
||||
|
||||
|
||||
def read_file(filename):
|
||||
file = open(filename, 'r')
|
||||
while True:
|
||||
line = file.readline()
|
||||
if not line:
|
||||
break
|
||||
yield line.strip()
|
||||
|
||||
def find_formula(formula, rules):
|
||||
steps = 0
|
||||
f = formula
|
||||
while formula != 'e':
|
||||
start = formula
|
||||
for k,v in rules:
|
||||
if v in formula:
|
||||
steps += 1
|
||||
formula = formula.replace(v, k, 1)
|
||||
|
||||
if formula == start:
|
||||
shuffle(rules)
|
||||
steps = 0
|
||||
formula = f
|
||||
|
||||
return steps
|
||||
|
||||
def main():
|
||||
medicine = ""
|
||||
rules = []
|
||||
for line in read_file('input'):
|
||||
# skip empty lines
|
||||
if not line:
|
||||
continue
|
||||
match = re.match(RE_RULE, line)
|
||||
if match:
|
||||
rules.append((match.group(1), match.group(2)))
|
||||
else:
|
||||
medicine = line
|
||||
|
||||
print rules
|
||||
print medicine
|
||||
print find_formula(medicine, rules)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user