Created
December 5, 2022 20:29
-
-
Save jsbueno/89bf6e37f78914beee4d6e7c8a7dd03c to your computer and use it in GitHub Desktop.
Advent of code, 5, Dec 2022
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
( https://adventofcode.com/2022/day/5 ) | |
SPOILER ALERT! | |
Instead of the end-to-end solution, just the class I've used | |
which can display the animation of containers been | |
moved around - | |
(not a good class, tough, -it is too "dumb" | |
""" | |
class Yard: | |
maxheight = 35 | |
def __init__(self, state): | |
*lines, names = state.split("\n") | |
self.stacks = {name:[] for name in names.split()} | |
for line in reversed(lines): | |
for stack, crate in zip(self.stacks, (line[i:i+4] for i in range(0, len(line), 4 ))) : | |
crate = crate.strip("[] ") | |
if not crate: continue | |
self.stacks[stack].append(crate) | |
def __repr__(self): | |
output = "" | |
for height in range(self.maxheight, -1, -1): | |
line = " ".join((f"[{stack[height]}]" if len(stack) > height else " ") for stack in self.stacks.values()) | |
output += line + "\n" | |
output += " ".join(f"{stack:^3s}" for stack in self.stacks) + "\n" | |
return output | |
def move(self, command, anim=True): | |
_, amount, _, origin, _ ,dest = command.split() | |
for move in range(int(amount)): | |
self.stacks[dest].append(self.stacks[origin].pop()) | |
if anim: | |
print(self) | |
sleep(0.005) | |
def move9001(self, command, anim=True): | |
_, amount, _, origin, _ ,dest = command.split() | |
amount = int(amount) | |
self.stacks[dest].extend(self.stacks[origin][-amount:]) | |
self.stacks[origin][-amount:] = [] | |
if anim: | |
print(self) | |
sleep(0.025) | |
def state(self): | |
return "".join(stack[-1] for stack in self.stacks.values()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment