summaryrefslogtreecommitdiff
path: root/2024/aoc2024-d04.py
diff options
context:
space:
mode:
Diffstat (limited to '2024/aoc2024-d04.py')
-rw-r--r--2024/aoc2024-d04.py62
1 files changed, 62 insertions, 0 deletions
diff --git a/2024/aoc2024-d04.py b/2024/aoc2024-d04.py
new file mode 100644
index 0000000..c999c83
--- /dev/null
+++ b/2024/aoc2024-d04.py
@@ -0,0 +1,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);