aoc/2022/day05.py

80 lines
1.6 KiB
Python

#!/usr/bin/env python3
import copy
from typing import TextIO
arrangement = {}
arr_actual = {}
move_instr = []
def rearrange(arr: dict, old: int, new: int, times: int) -> None:
for _ in range(times):
move = arr[old].pop()
arr[new].append(move)
def rearrange_new(arr: dict, old: int, new: int, num: int) -> None:
move = arr[old][len(arr[old]) - num :]
arr[old] = arr[old][: len(arr[old]) - num]
arr[new] = arr[new] + move
def part1(f: TextIO) -> str:
top = ""
line = f.readline().rstrip()
while line.split()[0].isdigit() != True:
for x in range(1, len(line), 4):
stack = (x + 3) // 4
c = line[x]
if c.isalpha():
if stack not in arrangement:
arrangement[stack] = [c]
else:
arrangement[stack].insert(0, c)
line = f.readline()
global arr_actual
arr_actual = copy.deepcopy(arrangement)
f.readline()
line = f.readline()
while line != "":
line = line.split(" ")
# for part 2
move_instr.append(line)
rearrange(arrangement, int(line[3]), int(line[5]), int(line[1]))
line = f.readline().strip()
for i in sorted(arrangement.keys()):
top += arrangement[i][-1]
return top
def part2() -> str:
top = ""
for it in move_instr:
rearrange_new(arr_actual, int(it[3]), int(it[5]), int(it[1]))
for i in sorted(arr_actual.keys()):
top += arr_actual[i][-1]
return top
if __name__ == "__main__":
print(part1(open("day05.txt")))
print(part2())