From 7bf24fbbdb625de98ac2ff4dc5fd068b8f732d71 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Fri, 13 Dec 2024 02:52:07 +0100 Subject: [PATCH] 2024: Add day 12 --- 2024/12/1.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2024/12/2.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100755 2024/12/1.py create mode 100755 2024/12/2.py diff --git a/2024/12/1.py b/2024/12/1.py new file mode 100755 index 0000000..56692d4 --- /dev/null +++ b/2024/12/1.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import sys + +def parse(): + G = [] + for l in sys.stdin: + G.append([c for c in l.strip()]) + return G + +def cost(G): + def get(i, j): + if i < 0 or j < 0 or i >= len(G) or j >= len(G[0]): + return None + return G[i][j] + + stk = [] + seen = set() + tot = 0 + for i0 in range(len(G)): + for j0 in range(len(G[0])): + if (i0, j0) not in seen: + stk.append((i0, j0)) + # explore the plot + a = 0 + p = 0 + while stk: + (i, j) = stk.pop() + seen.add((i, j)) + crop = G[i][j] + a += 1 + for n in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]: + if get(n[0],n[1]) == crop: + if n not in seen: + seen.add(n) + stk.append(n) + else: + p += 1 + # print((crop, i, j, a, p)) + tot += a*p + return tot + +if __name__ == '__main__': + G = parse() + print(cost(G)) diff --git a/2024/12/2.py b/2024/12/2.py new file mode 100755 index 0000000..2eab9a2 --- /dev/null +++ b/2024/12/2.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +import sys + +def parse(): + G = [] + for l in sys.stdin: + G.append([c for c in l.strip()]) + return G + +def cost(G): + def get(i, j): + if i < 0 or j < 0 or i >= len(G) or j >= len(G[0]): + return None + return G[i][j] + + stk = [] + seen = set() + tot = 0 + for i0 in range(len(G)): + for j0 in range(len(G[0])): + if (i0, j0) not in seen: + stk.append((i0, j0)) + # explore the plot + a = 0 + p = 0 + while stk: + (i, j) = stk.pop() + seen.add((i, j)) + crop = G[i][j] + a += 1 + for n in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]: + if get(n[0],n[1]) == crop: + if n not in seen: + seen.add(n) + stk.append(n) + # unlike counting the perimeter, we count the + # _corners_ which is equivalent to the number of sides + for dy, dx in [(-1,-1),(-1,1),(1,-1),(1,1)]: + # outside corner is when both adjacent neighbors are diff + if get(i+dy,j) != crop and get(i,j+dx) != crop: + p += 1 + # inside corner is when both adjacent neighbors are same but diag diff + elif get(i+dy,j) == crop and get(i,j+dx) == crop and get(i+dy,j+dx) != crop: + p += 1 + # print((crop, i, j, a, p)) + tot += a*p + return tot + +if __name__ == '__main__': + G = parse() + print(cost(G)) -- libgit2 1.8.1