{ "cells": [ { "cell_type": "markdown", "id": "a19b0da1-9ac5-4d7f-9957-6268d3536564", "metadata": {}, "source": [ "### Part 1" ] }, { "cell_type": "code", "execution_count": 36, "id": "dc5032e6-5ad2-4b32-8a58-29679cfba227", "metadata": {}, "outputs": [], "source": [ "def split_def_in_sectors(line):\n", " for i in range(0, len(line), 4):\n", " yield line[i:i+3].strip()" ] }, { "cell_type": "code", "execution_count": 60, "id": "cdccaa3e-0aaf-4e0a-8171-179f90c65bb6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'VQZNJMWTR'" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "with open(\"aoc5_input.txt\", \"r\") as f:\n", " line = next(f).rstrip(\"\\n\")\n", " stacks = [[] for _ in range((len(line) + 1) // 4)]\n", " while \"[\" in line:\n", " for i, e in enumerate(split_def_in_sectors(line)):\n", " if e:\n", " stacks[i].append(e[1])\n", " line = next(f).rstrip(\"\\n\")\n", " next(f)\n", " for stack in stacks:\n", " stack.reverse()\n", " for cmd in f:\n", " match cmd.split():\n", " case [\"move\", amount, \"from\", pos, \"to\", newpos]:\n", " amount, pos, newpos = int(amount), int(pos)-1, int(newpos)-1\n", " stack_left, stack_right = stacks[pos][:-amount], reversed(stacks[pos][-amount:])\n", " stacks[pos] = stack_left\n", " stacks[newpos] += stack_right\n", "\n", "\"\".join(stack[-1] for stack in stacks)" ] }, { "cell_type": "markdown", "id": "b9df4a1d-f7ec-406c-870d-e5a7269ccf0c", "metadata": {}, "source": [ "### Part 2" ] }, { "cell_type": "code", "execution_count": 61, "id": "55ade032-7a23-4e6e-a984-71f0e452b224", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'NLCDCLVMQ'" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "with open(\"aoc5_input.txt\", \"r\") as f:\n", " line = next(f).rstrip(\"\\n\")\n", " stacks = [[] for _ in range((len(line) + 1) // 4)]\n", " while \"[\" in line:\n", " for i, e in enumerate(split_def_in_sectors(line)):\n", " if e:\n", " stacks[i].append(e[1])\n", " line = next(f).rstrip(\"\\n\")\n", " next(f)\n", " for stack in stacks:\n", " stack.reverse()\n", " for cmd in f:\n", " match cmd.split():\n", " case [\"move\", amount, \"from\", pos, \"to\", newpos]:\n", " amount, pos, newpos = int(amount), int(pos)-1, int(newpos)-1\n", " stack_left, stack_right = stacks[pos][:-amount], stacks[pos][-amount:]\n", " stacks[pos] = stack_left\n", " stacks[newpos] += stack_right\n", "\n", "\"\".join(stack[-1] for stack in stacks)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.7" } }, "nbformat": 4, "nbformat_minor": 5 }