From bcfe9de9af84c0718d938f78153a7cdda2999746 Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 5 Dec 2022 22:21:41 +0100 Subject: [PATCH] [py] Simplify 2022_05 --- py/aoc/y2022/d05.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/py/aoc/y2022/d05.py b/py/aoc/y2022/d05.py index 7ffba26..a059b16 100644 --- a/py/aoc/y2022/d05.py +++ b/py/aoc/y2022/d05.py @@ -1,32 +1,24 @@ def solve(inputstr): stackstr, movestr = inputstr.split("\n\n") - stacks = [] - for line in stackstr.splitlines()[:-1]: - i = 0 - while line: - crate, line = line[:3], line[4:] - if len(stacks) <= i: - stacks.append([]) - if crate[0] == "[": - stacks[i].append(crate[1]) - i += 1 - for stack in stacks: - stack.reverse() + stacklines = stackstr.splitlines()[:-1] + stacks = [[] for _ in range((len(stacklines[-1]) + 1) // 4)] + for line in stacklines[::-1]: + for i, c in enumerate(line[1::4]): + if c != " ": + stacks[i].append(c) moves = [] for line in movestr.splitlines(): _, amount, _, source, _, target = line.split() moves.append((int(amount), int(source), int(target))) - # Part 1 part1 = [list(stack) for stack in stacks] for amount, source, target in moves: - for _ in range(amount): - part1[target - 1].append(part1[source - 1].pop()) + part1[target - 1].extend(part1[source - 1][-amount:][::-1]) + part1[source - 1] = part1[source - 1][:-amount] print("Part 1:", "".join(stack[-1] for stack in part1)) - # Part 2 part2 = [list(stack) for stack in stacks] for amount, source, target in moves: part2[target - 1].extend(part2[source - 1][-amount:])