summaryrefslogtreecommitdiff
path: root/2020/aoc2020-d11.py
blob: 06c762692538f447804e590d59998d24851a4b13 (plain)
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
#advent of code 2020
#day 11

directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)];

#for part 1
def scan1(grid,pos):
	around = "";
	y,x = pos;
	for dy,dx in directions:
		if (y+dy,x+dx) not in grid: continue;
		around += grid[(y+dy,x+dx)];
	return around;
#for part 2
def scan2(grid,pos):
	around = "";
	for dy,dx in directions:
		y,x = pos;
		while True:
			x += dx;
			y += dy;
			if (y,x) not in grid: 
				break;
			elif grid[(y,x)] != ".":
				around += grid[(y,x)];
				break;
	return around;

#correct function is passed as an argument (scan)
def simulate(grid,scan,lim):
	score = 0;
	while True:
		gridDupe = dict();
		for coordinates in grid:
			state = grid[coordinates];
			y,x = coordinates;
			around = scan(grid,coordinates);
			if around.count("#") == 0 and state == "L": 
				gridDupe[coordinates] = "#";
			elif around.count("#") >= lim and state == "#":
				gridDupe[coordinates] = "L";
		for dupe in gridDupe: 
			grid[dupe] = gridDupe[dupe];
		if len(gridDupe) == 0: 
			break;
	for coordinates in grid: 
		if grid[coordinates] == "#": score += 1;
	return score;

grid1 = dict();
PuzzleInput = open("11.in","r");
for y,line in enumerate(PuzzleInput):
	line = line[:-1];
	for x, c in enumerate(line):
		grid1[(y,x)] = c;
PuzzleInput.close();
grid2 = grid1.copy(); 

p1 = simulate(grid1,scan1,4);
p2 = simulate(grid2,scan2,5);
print("part 1 =",p1);
print("part 2 =",p2);