-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc_day18.py
More file actions
108 lines (91 loc) · 2.08 KB
/
aoc_day18.py
File metadata and controls
108 lines (91 loc) · 2.08 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Advent of Code Day 18
def constructGrid(input):
x = 0
y = 0
for line in input:
lightsgrid.append([])
for light in line:
if light == '#':
lightsgrid[x].append(1)
elif light == '.':
lightsgrid[x].append(0)
else:
print('Wrong input')
y += 1
x += 1
y = 0
def gridToString():
tostring = ''
for line in lightsgrid:
for light in line:
if light > 0:
tostring += '#'
else:
tostring += '.'
tostring += '\n'
return tostring
def anyGridToString(anygrid):
tostring = ''
for line in anygrid:
for light in line:
if light > 0:
tostring += '#'
else:
tostring += '.'
tostring += '\n'
return tostring
def countOnNeighbors(x,y):
count = 0
for cy in range(y-1,y+2):
if cy >= 0 and cy < len(lightsgrid[x]):
for cx in range(x-1,x+2):
if cx >= 0 and cx < len(lightsgrid):
if not (cx == x and cy == y):
count += lightsgrid[cx][cy]
return count
def defineNewState(x,y):
state = 0
if lightsgrid[x][y] == 1:
# light is on
onNeighbors = countOnNeighbors(x,y)
if onNeighbors == 2 or onNeighbors == 3:
state = 1
else:
state = 0
elif lightsgrid[x][y] == 0:
# light is off
if 3 == countOnNeighbors(x,y):
state = 1
else:
state = 0
if x == 0:
if y == 0 or y == len(lightsgrid[x])-1:
state = 1
elif x == len(lightsgrid)-1:
if y == 0 or y == len(lightsgrid[x])-1:
state = 1
return state
def doOneStep():
newlightsgrid = []
for x in range(0,len(lightsgrid)):
newlightsgrid.append([])
for y in range(0,len(lightsgrid[x])):
newlightsgrid[x].append(defineNewState(x,y))
return newlightsgrid
def countOnLights():
count = 0
for x in range(0,len(lightsgrid)):
for y in range(0,len(lightsgrid[x])):
count += lightsgrid[x][y]
return count
lightsgrid = []
with open('aoc_day18_p2_input.txt') as f:
# with open('aoc_day18_input.txt') as f:
# with open('aoc_day18_test_input.txt') as f:
input = [line.strip() for line in f]
constructGrid(input)
print(gridToString())
for step in range(0,100):
lightsgrid = doOneStep()
# print(gridToString())
print('There are',countOnLights(),'lights on')