diff --git a/py/aoc/__init__.py b/py/aoc/__init__.py index 51c0e13..e66b473 100644 --- a/py/aoc/__init__.py +++ b/py/aoc/__init__.py @@ -4,7 +4,7 @@ from pathlib import Path from .y2020 import d10 from .y2021 import d14 -from .y2022 import d01, d02, d03, d04 +from .y2022 import d01, d02, d03, d04, d05 DAYS = { "2020_10": y2020.d10.solve, @@ -13,6 +13,7 @@ DAYS = { "2022_02": y2022.d02.solve, "2022_03": y2022.d03.solve, "2022_04": y2022.d04.solve, + "2022_05": y2022.d05.solve, } diff --git a/py/aoc/y2022/d05.py b/py/aoc/y2022/d05.py new file mode 100644 index 0000000..7ffba26 --- /dev/null +++ b/py/aoc/y2022/d05.py @@ -0,0 +1,34 @@ +def solve(inputstr): + stackstr, movestr = inputstr.split("\n\n") + + stacks = [] + for line in stackstr.splitlines()[:-1]: + i = 0 + while line: + crate, line = line[:3], line[4:] + if len(stacks) <= i: + stacks.append([]) + if crate[0] == "[": + stacks[i].append(crate[1]) + i += 1 + for stack in stacks: + stack.reverse() + + moves = [] + for line in movestr.splitlines(): + _, amount, _, source, _, target = line.split() + moves.append((int(amount), int(source), int(target))) + + # Part 1 + part1 = [list(stack) for stack in stacks] + for amount, source, target in moves: + for _ in range(amount): + part1[target - 1].append(part1[source - 1].pop()) + print("Part 1:", "".join(stack[-1] for stack in part1)) + + # Part 2 + part2 = [list(stack) for stack in stacks] + for amount, source, target in moves: + part2[target - 1].extend(part2[source - 1][-amount:]) + part2[source - 1] = part2[source - 1][:-amount] + print("Part 2:", "".join(stack[-1] for stack in part2))