From 89a16489cbe4c16c1e38364f6ea9a2173d59f9cf Mon Sep 17 00:00:00 2001 From: aaron Date: Mon, 5 Dec 2022 23:12:52 +0100 Subject: [PATCH] solve day 5 part a --- 5/supplystacks.py | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 5/supplystacks.py diff --git a/5/supplystacks.py b/5/supplystacks.py new file mode 100644 index 0000000..3218843 --- /dev/null +++ b/5/supplystacks.py @@ -0,0 +1,60 @@ +from copy import deepcopy +from aocd.models import Puzzle +from aocd import submit + + +def rearrange_stacks(stacks: dict, moves: list) -> str: + """ + execute moves on the stacks and return the top of each stack + """ + # take a deep copy so embedded list do not get messed up + stacks = deepcopy(stacks) + # for each move, execute on stacks + for amount, index, dest in moves: + for i in range(amount): + stacks[dest].append(stacks[index].pop()) + # take the last element fom each stack and append to output + return "".join([stack[-1] for stack in stacks.values()]) + + +def parse_input(data: list) -> list: + """ + turn input data into usable data types: + stacks_str -> dict of moves {'index':['A','B','C']} + moves_str -> list of opeations [amount, index, dest] + """ + # get input data + stacks_str, moves_str = data.split("\n\n") + # transpose field for easier parsing (thx linalg course) + transposed_stacks = list(map(list, zip(*stacks_str.splitlines()))) + # parse stacks + stacks = {} + for line in transposed_stacks[1::4]: + stack = [c for c in line if c != " "] + key = stack.pop() + stack.reverse() + stacks[key] = stack + # parse moves + moves = [] + for move in moves_str.splitlines(): + _, amount, _, index, _, dest = move.split(" ") + # print(f'move {amount} from {index} to {dest}') + moves.append((int(amount), index, dest)) + # return parsed data + return stacks, moves + + +if __name__ == "__main__": + # get puzzle and parse data + puzzle = Puzzle(year=2022, day=5) + stacks, moves = parse_input(puzzle.input_data) + + # part a: + answer_a = rearrange_stacks(stacks, moves) + print(f"{answer_a}") + submit(answer_a, part="a", day=5, year=2022) + + # part b: + answer_b = 0 + print(f"{answer_b}") + # submit(answer_b, part="b", day=5, year=2022)