added rest of the code

This commit is contained in:
Peter Hudec
2016-08-08 07:34:33 +02:00
parent a9ceb0715a
commit 1226b1e448
6 changed files with 180 additions and 1 deletions

5
19/input1 Normal file
View File

@ -0,0 +1,5 @@
H => HO
H => OH
O => HH
HOH

7
19/input2 Normal file
View File

@ -0,0 +1,7 @@
e => H
e => O
H => HO
H => OH
O => HH
HOHOHO

53
19/part1.py Normal file
View 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
View 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()

5
19/readme Normal file
View File

@ -0,0 +1,5 @@
## part1
python part1.py | sort -u | wc -l
## part2