aoc2022/day05.py

58 lines
1.7 KiB
Python

from tools.aoc import AOCDay
from typing import Any
class Day(AOCDay):
inputs = [
[
("CMZ", "input5_test"),
("VJSFHWGFT", "input5_dennis"),
("WSFTMRHPP", "input5"),
],
[
("MCD", "input5_test"),
("LCTQFBVZV", "input5_dennis"),
("GSLCMFBRP", "input5"),
]
]
def get_stacks_and_moves(self) -> (dict, list):
i = self.getInput()
stacks = {}
for l, line in enumerate(i):
if not line:
return stacks, i[l+1:]
this_stacks = (len(line) + 1) // 4
for stack_num in range(this_stacks):
crate = line[stack_num * 4 + 1]
if ord(crate) > 64:
if stack_num + 1 not in stacks:
stacks[stack_num + 1] = []
stacks[stack_num + 1].append(crate)
def part1(self) -> Any:
stacks, moves = self.get_stacks_and_moves()
for move in moves:
l = move.split(" ")
count, move_from, move_to = map(int, [l[1], l[3], l[5]])
for _ in range(count):
stacks[move_to].insert(0, stacks[move_from].pop(0))
return "".join(stacks[x].pop(0) for x in sorted(stacks))
def part2(self) -> Any:
stacks, moves = self.get_stacks_and_moves()
for move in moves:
l = move.split(" ")
count, move_from, move_to = map(int, [l[1], l[3], l[5]])
stacks[move_to] = stacks[move_from][:count] + stacks[move_to]
stacks[move_from] = stacks[move_from][count:]
return "".join(stacks[x].pop(0) for x in sorted(stacks))
if __name__ == '__main__':
day = Day(2022, 5)
day.run(verbose=True)