#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);