Solve 2022 day 5 pt 1-2
Important not to strip trailing whitespace from this one :)
This commit is contained in:
parent
ea1143d591
commit
cb03569794
1 changed files with 46 additions and 0 deletions
46
2022-python/output/day_05.py
Normal file
46
2022-python/output/day_05.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
from copy import deepcopy
|
||||
from collections import defaultdict
|
||||
|
||||
from output import ints
|
||||
|
||||
|
||||
def solve(data):
|
||||
state, program = data.split("\n\n")
|
||||
labels, *state = state.splitlines()[::-1]
|
||||
num = max(ints(labels))
|
||||
stacks = defaultdict(list)
|
||||
for r, text in enumerate(state):
|
||||
for c in range(4 * num):
|
||||
if c % 4 == 1:
|
||||
if text[c] != " ":
|
||||
stacks[c // 4 + 1].append(text[c])
|
||||
p1 = _act(program, deepcopy(stacks))
|
||||
p2 = _act(program, deepcopy(stacks), r=9001)
|
||||
return p1, p2
|
||||
|
||||
|
||||
def _act(program, stacks, r=9000):
|
||||
for line in program.splitlines():
|
||||
count, old, new = ints(line)
|
||||
match r:
|
||||
case 9000:
|
||||
for _ in range(count):
|
||||
if stacks[old]:
|
||||
stacks[new].append(stacks[old].pop())
|
||||
case 9001:
|
||||
stacks[new] += stacks[old][-count:]
|
||||
stacks[old] = stacks[old][:-count]
|
||||
return "".join(s[-1] for s in stacks.values())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
with open("./input/05.txt", "r") as f:
|
||||
inp = f.read()
|
||||
|
||||
p1, p2 = solve(inp)
|
||||
|
||||
print(p1)
|
||||
print(p2)
|
||||
|
||||
assert p1 == "ZRLJGSCTR"
|
||||
assert p2 == "PRTTGRFPB"
|
||||
Loading…
Add table
Reference in a new issue