From d862c3ecfbd1b9ebdf67a835a56c5996c1e2de22 Mon Sep 17 00:00:00 2001 From: Joscha Date: Fri, 9 Dec 2022 15:18:56 +0100 Subject: [PATCH] [py] Solve 2022_09 --- py/aoc/__init__.py | 3 ++- py/aoc/y2022/d09.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 py/aoc/y2022/d09.py diff --git a/py/aoc/__init__.py b/py/aoc/__init__.py index 802a137..7c9987f 100644 --- a/py/aoc/__init__.py +++ b/py/aoc/__init__.py @@ -8,7 +8,7 @@ from .y2017 import d01, d02, d03, d04, d05, d06, d07, d08, d09 from .y2018 import d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11 from .y2020 import d10 from .y2021 import d14 -from .y2022 import d01, d02, d03, d04, d05, d06, d07 +from .y2022 import d01, d02, d03, d04, d05, d06, d07, d09 DAYS = { # 2015 @@ -58,6 +58,7 @@ DAYS = { "2022_05": y2022.d05.solve, "2022_06": y2022.d06.solve, "2022_07": y2022.d07.solve, + "2022_09": y2022.d09.solve, } diff --git a/py/aoc/y2022/d09.py b/py/aoc/y2022/d09.py new file mode 100644 index 0000000..68efc1c --- /dev/null +++ b/py/aoc/y2022/d09.py @@ -0,0 +1,25 @@ +def sign(n): + return 0 if n == 0 else n // abs(n) + + +def simulate_rope(input, segments): + knots = [[0, 0] for _ in range(segments)] + trail = {(0, 0)} + for line in input.splitlines(): + direction, amount = line.split() + hdx, hdy = {"L": (-1, 0), "R": (1, 0), "D": (0, -1), "U": (0, 1)}[direction] + for _ in range(int(amount)): + knots[0][0] += hdx + knots[0][1] += hdy + for i in range(1, len(knots)): + dx, dy = knots[i - 1][0] - knots[i][0], knots[i - 1][1] - knots[i][1] + if abs(dx) > 1 or abs(dy) > 1: + knots[i][0] += sign(dx) + knots[i][1] += sign(dy) + trail.add(tuple(knots[-1])) + return len(trail) + + +def solve(inputstr): + print(f"Part 1: {simulate_rope(inputstr, 2)}") + print(f"Part 2: {simulate_rope(inputstr, 10)}")