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
|
#advent of code 2020
#day 24
# https://www.redblobgames.com/grids/hexagons/
# nested ifs in CheckAdjacent function aren't really slower than
# making it a function, so i'm leaving it bc its more readable that way
def CheckAdjacent(point, blackset):
black = 0;
py,px,pz = point;
for dkey in directions:
dx,dy,dz = directions[dkey];
p = (py+dy,px+dx, pz+dz);
if p in blackset:
black += 1;
if point in blackset:
if black == 0 or black > 2:
return False;
else:
return True;
else:
if black == 2:
return True;
else:
return False;
tilesteps = [];
PuzzleInput = open("24.in","r")
for line in PuzzleInput:
line = line.replace("\n","");
instructions = [];
i = 0;
while i < len(line):
if line[i] in ["n","s"]:
instructions.append(line[i:i+2]);
i += 2;
else:
instructions.append(line[i]);
i += 1;
tilesteps.append(instructions);
PuzzleInput.close();
directions = dict();
directions["e"] = (1,0,-1);
directions["w"] = (-1,0,1);
directions["ne"] = (1,-1,0);
directions["nw"] = (0,-1,1);
directions["sw"] = (-1,1,0);
directions["se"] = (0,1,-1);
grid = dict();
# 0 - white
# 1 - black
for tilestep in tilesteps:
p = (0,0,0);
for step in tilestep:
py,px,pz = p;
dy,dx,dz = directions[step];
p = (py+dy,px+dx, pz+dz);
grid[p] = ( grid.get(p,0) + 1)%2;
blacks = set();
part1 = 0;
for g in grid:
if grid[g] == 1:
part1 += 1;
blacks.add(g);
print("part 1 =", part1);
days = 100;
for day in range(days):
NewBlacks = set();
for b in blacks:
if CheckAdjacent(b,blacks): NewBlacks.add(b);
for coord in directions.values():
n = (b[0] + coord[0],b[1] + coord[1],b[2] + coord[2]);
if CheckAdjacent(n,blacks): NewBlacks.add(n);
blacks = set();
blacks.update(NewBlacks);
part2 = len(blacks);
print("part 2 =", part2);
|