From 7290f28ef760052092e3c6b3547ab20d698ffadf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Sun, 3 Dec 2023 08:44:35 +0100 Subject: [PATCH] Solve 2023:03 "Gear Ratios" Overslept, took about 55 mins. --- 2023-python/output/day_03.py | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 2023-python/output/day_03.py diff --git a/2023-python/output/day_03.py b/2023-python/output/day_03.py new file mode 100644 index 0000000..ee8c7f2 --- /dev/null +++ b/2023-python/output/day_03.py @@ -0,0 +1,68 @@ +from collections import deque +from output import answer, puzzleinput + +n = 3 +title = "Gear Ratios" + + +@answer(1, "Sum of all part numbers is {} in the engine schematic") +def part_1(presolved): + s, _ = presolved + return s + + +@answer(2, "Gear ratio sums is {} in the engine schematic") +def part_2(presolved): + _, gr = presolved + return gr + + +def presolve(data): + adj = (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1) + w = len(data[0]) + h = len(data) + s = list() + gr = list() + for y in range(w): + for x in range(h): + if data[y][x] != "." and not data[y][x].isdigit(): + seen = set() + t = list() + for oy, ox in adj: + if (y + oy, x + ox) in seen: + continue + if data[y + oy][x + ox].isdigit(): + n = deque([data[y + oy][x + ox]]) + i = x + ox - 1 + while i in range(w) and data[y + oy][i].isdigit(): + n.append(data[y + oy][i]) + seen.add((y + oy, i)) + i -= 1 + i = x + ox + 1 + while i in range(w) and data[y + oy][i].isdigit(): + n.appendleft(data[y + oy][i]) + seen.add((y + oy, i)) + i += 1 + t.append(sum(10**m * int(d) for m, d in enumerate(n))) + # part 1 + s.append(sum(t)) + # part 2 + if data[y][x] == "*" and len(t) == 2: + a, b = t + gr.append(a * b) + + return sum(s), sum(gr) + + +@puzzleinput(n) +def parse_input(data): + return data.split() + + +if __name__ == "__main__": + parsed = presolve(parse_input()) + a = part_1(parsed) + b = part_2(parsed) + + assert a == 553825 + assert b == 93994191