advent-of-code/2022/5/5.py
2022-12-05 09:15:00 +01:00

84 lines
No EOL
2.2 KiB
Python

"""
rearrange a list of crates one by one according to given instructions
"""
import re
from string import ascii_letters
instruction_pattern = re.compile(r'(\d+)')
class CrateMover9000:
def __init__(self, plan:str) -> None:
self.numstacks = len(instruction_pattern.findall(plan.pop()))
self.stacks = [[] for _ in range(self.numstacks)]
for i in range(len(plan)):
layer = f"{plan.pop():<{self.numstacks*4}}"
crates = layer[1::4]
for j, crate in enumerate(crates):
if crate in ascii_letters:
self.stacks[j].append(crate)
def move(self, instruction:str) -> None:
num, source, target = [int(s) for s in instruction_pattern.findall(instruction)]
for _ in range(num):
self.stacks[target-1].append(self.stacks[source-1].pop())
def shuffle(self, insttructions:str) -> None:
for line in instructions:
self.move(line)
def show(self) -> None:
for i, stack in enumerate(self.stacks):
print(i+1,*stack)
print("")
def top_crates(self) -> str:
s = ''
for stack in self.stacks:
s += stack[-1]
return s
text = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
"""
with open('2022/5/crane.txt') as filein:
text = filein.read()
plan, instructions = [t.splitlines(keepends=False) for t in text.split('\n\n')]
crane = CrateMover9000(plan)
crane.show()
crane.shuffle(instructions)
crane.show()
print("top message:", crane.top_crates())
"""
now rearrange a list of crates in batches according to given instructions
"""
class CrateMover9001(CrateMover9000):
def __init__(self, plan: str) -> None:
super().__init__(plan)
def move(self, instruction: str) -> None:
num, source, target = [int(s) for s in instruction_pattern.findall(instruction)]
self.stacks[target-1] += self.stacks[source-1][-num:]
self.stacks[source-1] = self.stacks[source-1][:-num]
plan, instructions = [t.splitlines(keepends=False) for t in text.split('\n\n')]
crane = CrateMover9001(plan)
crane.shuffle(instructions)
crane.show()
print("top message:", crane.top_crates())