-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc_day19.py
More file actions
85 lines (68 loc) · 1.79 KB
/
aoc_day19.py
File metadata and controls
85 lines (68 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Advent of Code Day 19
import re
molecule = ''
replacementRules = []
possibleOriginElements = set()
replacementPattern = re.compile('(.*) => (.*)')
def registerInput(input):
global molecule
for inp in input:
matches = replacementPattern.match(inp)
if matches:
origin = matches.group(1)
replacementRules.append((origin,matches.group(2)))
if origin not in possibleOriginElements:
possibleOriginElements.add(origin)
else:
print('input:#'+inp+'#')
if inp != '':
print('mol')
molecule = inp
def splitMolecule(mol):
splitted = []
pos = 0
while pos < len(mol):
atom = ''
if pos < len(mol)-1:
if str(mol[pos+1]).islower():
atom = mol[pos:pos+2]
pos += 2
splitted.append(atom)
continue
atom = mol[pos]
pos += 1
splitted.append(atom)
return splitted
def makeNewMolecule(upToPos,replaceAtom):
prefix = splittedMolecule[:upToPos]
prefix.append(replaceAtom)
postfix = splittedMolecule[upToPos+1:]
print(upToPos,'pre',prefix)
print(upToPos,'pos',postfix)
return prefix+postfix
def makeMoleculeStr(mollist):
mol = ''
for atom in mollist:
mol += atom
return mol
with open('aoc_day19_input.txt') as f:
# with open('aoc_day19_test_input.txt') as f:
input = [line.strip() for line in f]
registerInput(input)
print(replacementRules)
print(possibleOriginElements)
print(molecule)
splittedMolecule = splitMolecule(molecule)
replacedMolecule = set()
posInMol = 0
for atom in splittedMolecule:
replaced = False
if atom in possibleOriginElements:
for rule in replacementRules:
if rule[0] == atom:
newmol = makeMoleculeStr(makeNewMolecule(posInMol,rule[1]))
if newmol not in replacedMolecule:
replacedMolecule.add(newmol)
posInMol += 1
print(replacedMolecule)
print('It seems there are',len(replacedMolecule),'different molecules')