From 612b61a1ac20d85e279379a000deeb313ec7fee5 Mon Sep 17 00:00:00 2001 From: Sijmen Date: Mon, 5 Dec 2022 10:39:58 +0100 Subject: [PATCH] day 5, but mildly less cursed --- day05.py | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/day05.py b/day05.py index e26daa7..1a4f8e5 100644 --- a/day05.py +++ b/day05.py @@ -1,42 +1,27 @@ import fileinput +import sys from collections import defaultdict, deque import re from copy import deepcopy -input = fileinput.input() -stacks: list[deque] = [] - -for y, line in enumerate(input): - line = line.rstrip("\n") - if "1" in line: - continue - if not line: - break - - for x in range(0, len(line), 4): - if y == 0: - stacks.append(deque([line[x + 1]] if line[x + 1] != " " else [])) - elif line[x + 1] != " ": - stacks[x // 4].appendleft(line[x + 1]) +input = sys.stdin.read().split("\n") +rows = (line[1::4] for line in input[::-1] if "[" in line) +stacks = [[c for c in x if c != ' '] for x in zip(*rows)] stacks2 = deepcopy(stacks) - + RE = re.compile(r"move (\d+) from (\d+) to (\d+)") for line in input: m = RE.match(line) if not m: continue - n, f, t = int(m[1]), int(m[2]), int(m[3]) + n, f, t = int(m[1]), int(m[2]) - 1, int(m[3]) - 1 - p2stack = [] - for _ in range(n): - c = stacks[f - 1].pop() - stacks[t - 1].append(c) + stacks[t].extend(reversed(stacks[f][-n:])) + del stacks[f][-n:] - c = stacks2[f - 1].pop() - p2stack.append(c) - - stacks2[t - 1].extend(reversed(p2stack)) + stacks2[t].extend(stacks2[f][-n:]) + del stacks2[f][-n:] print("".join(s[-1] for s in stacks), "".join(s[-1] for s in stacks2))