solve day 5 part a
This commit is contained in:
60
5/supplystacks.py
Normal file
60
5/supplystacks.py
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user