{ "cells": [ { "cell_type": "code", "execution_count": 91, "id": "opening-munich", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "def new_grid(n):\n", " return np.zeros((n,n), np.int64)\n", "\n", "def parse_points(seg):\n", " start, end = seg.rstrip().split(' -> ')\n", " x1, y1 = map(int, start.split(','))\n", " x2, y2 = map(int, end.split(','))\n", " return x1, y1, x2, y2\n", "\n", "def slice_range(x1, y1, x2, y2):\n", " if y1 > y2:\n", " y = range(y1, y2-1, -1)\n", " else:\n", " y = range(y1, y2+1)\n", " \n", " if x1 > x2:\n", " x = range(x1, x2-1, -1)\n", " else:\n", " x = range(x1, x2+1)\n", " \n", " return (y, x)\n", " \n", "\n", "def grid_slice(grid, seg, diagonal):\n", " x1, y1, x2, y2 = parse_points(seg)\n", " if y1 == y2 or x1 == x2 or diagonal:\n", " return slice_range(x1, y1, x2, y2)\n", " else:\n", " return None\n", "\n", "def overlapping(grid, f, diagonal=False):\n", " for l in f.splitlines():\n", " s = grid_slice(grid, l, diagonal)\n", " if s is not None:\n", " grid[s] += 1\n", " return np.sum(grid >= 2)" ] }, { "cell_type": "code", "execution_count": 93, "id": "colonial-karen", "metadata": {}, "outputs": [], "source": [ "g = new_grid(10)\n", "test = \"\"\"0,9 -> 5,9\n", "8,0 -> 0,8\n", "9,4 -> 3,4\n", "2,2 -> 2,1\n", "7,0 -> 7,4\n", "6,4 -> 2,0\n", "0,9 -> 2,9\n", "3,4 -> 1,4\n", "0,0 -> 8,8\n", "5,5 -> 8,2\"\"\"\n", "assert overlapping(g, test) == 5\n", "g = new_grid(10)\n", "assert overlapping(g, test, diagonal=True) == 12" ] }, { "cell_type": "code", "execution_count": 50, "id": "russian-skiing", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5280" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import import_ipynb\n", "import helper\n", "f = helper.read_file('2021_5.txt')\n", "g = new_grid(1000)\n", "overlapping(g, f)" ] }, { "cell_type": "code", "execution_count": 94, "id": "catholic-glory", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "16716" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g = new_grid(1000)\n", "overlapping(g, f, diagonal=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "superior-purple", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.9.2" }, "title": "Hydrothermal Venture" }, "nbformat": 4, "nbformat_minor": 5 }