[py] Solve 2022_05

This commit is contained in:
Joscha 2022-12-05 12:13:08 +01:00
parent ff469b2afb
commit 0e1afe2017
2 changed files with 36 additions and 1 deletions

View file

@ -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,
}

34
py/aoc/y2022/d05.py Normal file
View file

@ -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))