-
Notifications
You must be signed in to change notification settings - Fork 0
/
day12.py
74 lines (53 loc) · 1.61 KB
/
day12.py
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
import re
def load(filename):
file = open(filename)
header = file.readline()
plants = list(
map(lambda x: True if x == '#' else False,
re.findall(r"[#.]+", header)[0]))
file.readline()
rules = set()
for line in file.readlines():
m = re.match(r"([.#]{5}) => ([.#])", line)
if m[2] == "#":
rules.add(tuple(map(lambda x: True if x == '#' else False, m[1])))
return plants, rules
def grow(plants, rules, startIdx=0):
res = []
paddedPlants = [False, False, False] + plants + [False, False, False]
for i in range(2, len(paddedPlants)-2):
state = (paddedPlants[i-2],
paddedPlants[i-1],
paddedPlants[i],
paddedPlants[i+1],
paddedPlants[i+2])
if state in rules:
if not res:
startIdx = startIdx + i-3
res.append(True)
else:
if res:
res.append(False)
return res, startIdx
def plantsStr(plants):
return "".join(map(lambda x: '#' if x else '.', plants))
plants, rules = load('day12.txt')
idx = 0
previdx = 0
prevplants = []
for i in range(200):
print(i, idx, plantsStr(plants))
plants, idx = grow(plants, rules, idx)
if prevplants == plants:
print("we're done")
break
prevplants = plants
# at this point the pattern does not change, but will move in one direction
# thus we can calculate future index
idx = (50000000000 - i-1) + idx
# sum it
sum = 0
for i, plant in enumerate(plants):
if plant:
sum += idx+i
print("Solution 2", sum, i)