Skip to content

Instantly share code, notes, and snippets.

@jonaslindmark
Created December 7, 2022 12:42
Show Gist options
  • Save jonaslindmark/476976ec77d1e2e245b5fd1934a81131 to your computer and use it in GitHub Desktop.
Save jonaslindmark/476976ec77d1e2e245b5fd1934a81131 to your computer and use it in GitHub Desktop.
import sys
from collections import defaultdict
infile = open("5.in")
inlines = [l for l in infile]
stacks = defaultdict(list)
def part1():
boxparsing = True
def take(move, from_, to_):
f = stacks[int(from_)]
t = stacks[int(to_)]
for _ in range(int(move)):
t.append(f.pop())
for line in inlines:
if boxparsing:
for i in range(0, len(line), 4):
if line[i] == "[":
stack = int(i / 4) + 1
stacks[stack].insert(0, line[i+1])
if not line.strip():
boxparsing = False
else:
parts = line.split()
_, count, _, from_, _, to_ = parts
take(count, from_, to_)
boxes = [stacks[i][-1] for i in sorted(stacks.keys())]
print("part1", "".join(boxes))
def part2():
boxparsing = True
def take(move, from_, to_):
f = stacks[int(from_)]
t = stacks[int(to_)]
tomove = []
for _ in range(int(move)):
tomove.append(f.pop())
t.extend(reversed(tomove))
for line in inlines:
if boxparsing:
for i in range(0, len(line), 4):
if line[i] == "[":
stack = int(i / 4) + 1
stacks[stack].insert(0, line[i+1])
if not line.strip():
boxparsing = False
else:
parts = line.split()
_, count, _, from_, _, to_ = parts
take(count, from_, to_)
boxes = [stacks[i][-1] for i in sorted(stacks.keys())]
print("part2", "".join(boxes))
part1()
part2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment