summaryrefslogtreecommitdiff
path: root/2024/aoc2024-d04.py
blob: c999c83386ded48fda76caf0463145fd77fdd4d6 (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 2024
#day 04
#the issue with 1st version of part 2 was that I didn't account for
#a cross of words "MAM" and "SAS"
#counting the letters gave a false positive (number of "m" and "s" was the same
#but it wasn't a cross of 2 "MAS" words
#now it check independently each word (dirs1 and dirs2)

part1 = 0;
part2 = 0;
word = "XMAS";
dirs = ((1,0),(-1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,1),(1,-1));
Alist = [];
grid = {};
xm = 0;
ym = 0;

f = open("04.in","r")
for y,l in enumerate(f):
	ym = y +1;
	l = l[:-1];
	for x,c in enumerate(l):
		xm = x +1;
		grid[(x,y)] = c;
f.close();

for y in range(ym):
	for x in range(xm):
		if grid[(x,y)] == "A": Alist.append((x,y));
		for d in dirs:
			dx, dy = d;
			IsWord = True;
			for i in range(len(word)):
				nx = x + dx*i;
				ny = y + dy*i;
				nc = grid.get((nx,ny),"q");
				if nc != word[i]:
					IsWord = False;
					break;
			if IsWord: part1 += 1;

dirs1 = ((-1,-1),(1,1));
dirs2 = ((-1,1),(1,-1));
dirs0 = [dirs1,dirs2];
for A in Alist:
	x,y = A;
	xcount = 0;
	for d0 in dirs0:
		cross = {};
		for d in d0:
			dx,dy = d;
			nx = x + dx;
			ny = y + dy;
			c = grid.get((nx,ny),"q");
			v = cross.get(c,0);
			cross[c] = v + 1;
		if cross.get("S",0) == 1 and cross.get("M",0) ==1:
			xcount += 1;
	if xcount == 2: part2 += 1;

print("part 1 =", part1);
print("part 2 =", part2);