{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Advent of Code 2017\n",
    "\n",
    "## December 3rd\n",
    "\n",
    "You come across an experimental new kind of memory stored on an infinite two-dimensional grid.\n",
    "\n",
    "Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:\n",
    "\n",
    "    17  16  15  14  13\n",
    "    18   5   4   3  12\n",
    "    19   6   1   2  11\n",
    "    20   7   8   9  10\n",
    "    21  22  23---> ...\n",
    "\n",
    "While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1.\n",
    "\n",
    "For example:\n",
    "\n",
    "* Data from square 1 is carried 0 steps, since it's at the access port.\n",
    "* Data from square 12 is carried 3 steps, such as: down, left, left.\n",
    "* Data from square 23 is carried only 2 steps: up twice.\n",
    "* Data from square 1024 must be carried 31 steps.\n",
    "\n",
    "How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Analysis\n",
    "\n",
    "I freely admit that I worked out the program I wanted to write using graph paper and some Python doodles.  There's no point in trying to write a Joy program until I'm sure I understand the problem well enough.\n",
    "\n",
    "The first thing I did was to write a column of numbers from 1 to n (32 as it happens) and next to them the desired output number, to look for patterns directly:\n",
    "\n",
    "    1  0\n",
    "    2  1\n",
    "    3  2\n",
    "    4  1\n",
    "    5  2\n",
    "    6  1\n",
    "    7  2\n",
    "    8  1\n",
    "    9  2\n",
    "    10 3\n",
    "    11 2\n",
    "    12 3\n",
    "    13 4\n",
    "    14 3\n",
    "    15 2\n",
    "    16 3\n",
    "    17 4\n",
    "    18 3\n",
    "    19 2\n",
    "    20 3\n",
    "    21 4\n",
    "    22 3\n",
    "    23 2\n",
    "    24 3\n",
    "    25 4\n",
    "    26 5\n",
    "    27 4\n",
    "    28 3\n",
    "    29 4\n",
    "    30 5\n",
    "    31 6\n",
    "    32 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are four groups repeating for a given \"rank\", then the pattern enlarges and four groups repeat again, etc.\n",
    "\n",
    "            1 2\n",
    "          3 2 3 4\n",
    "        5 4 3 4 5 6\n",
    "      7 6 5 4 5 6 7 8\n",
    "    9 8 7 6 5 6 7 8 9 10\n",
    "\n",
    "Four of this pyramid interlock to tile the plane extending from the initial \"1\" square.\n",
    "\n",
    "\n",
    "             2   3   |    4  5   |    6  7   |    8  9\n",
    "          10 11 12 13|14 15 16 17|18 19 20 21|22 23 24 25\n",
    "\n",
    "And so on."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can figure out the pattern for a row of the pyramid at a given \"rank\" $k$:\n",
    "\n",
    "$2k - 1, 2k - 2, ..., k, k + 1, k + 2, ..., 2k$\n",
    "\n",
    "or\n",
    "\n",
    "$k + (k - 1), k + (k - 2), ..., k, k + 1, k + 2, ..., k + k$\n",
    "\n",
    "This shows that the series consists at each place of $k$ plus some number that begins at $k - 1$, decreases to zero, then increases to $k$.  Each row has $2k$ members."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's figure out how, given an index into a row, we can calculate the value there.  The index will be from 0 to $k - 1$. \n",
    "\n",
    " Let's look at an example, with $k = 4$:\n",
    "\n",
    "    0 1 2 3 4 5 6 7\n",
    "    7 6 5 4 5 6 7 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "k = 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Subtract $k$ from the index and take the absolute value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4 3 2 1 0 1 2 3\n"
     ]
    }
   ],
   "source": [
    "for n in range(2 * k):\n",
    "    print abs(n - k),"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not quite. Subtract $k - 1$ from the index and take the absolute value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3 2 1 0 1 2 3 4\n"
     ]
    }
   ],
   "source": [
    "for n in range(2 * k):\n",
    "    print abs(n - (k - 1)),"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Great, now add $k$..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7 6 5 4 5 6 7 8\n"
     ]
    }
   ],
   "source": [
    "for n in range(2 * k):\n",
    "    print abs(n - (k - 1)) + k,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So to write a function that can give us the value of a row at a given index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def row_value(k, i):\n",
    "    i %= (2 * k)  # wrap the index at the row boundary.\n",
    "    return abs(i - (k - 1)) + k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9 8 7 6 5 6 7 8 9 10\n"
     ]
    }
   ],
   "source": [
    "k = 5\n",
    "for i in range(2 * k):\n",
    "    print row_value(k, i),"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(I'm leaving out details of how I figured this all out and just giving the relevent bits.  It took a little while to zero in of the aspects of the pattern that were important for the task.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finding the rank and offset of a number.\n",
    "Now that we can compute the desired output value for a given rank and the offset (index) into that rank, we need to determine how to find the rank and offset of a number.\n",
    "\n",
    "The rank is easy to find by iteratively stripping off the amount already covered by previous ranks until you find the one that brackets the target number.  Because each row is $2k$ places and there are $4$ per rank each rank contains $8k$ places.  Counting the initial square we have:\n",
    "\n",
    "$corner_k = 1 + \\sum_{n=1}^k 8n$\n",
    "\n",
    "I'm not mathematically sophisticated enough to turn this directly into a formula (but Sympy is, see below.)  I'm going to write a simple Python function to iterate and search:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rank_and_offset(n):\n",
    "    assert n >= 2  # Guard the domain.\n",
    "    n -= 2  # Subtract two,\n",
    "            # one for the initial square,\n",
    "            # and one because we are counting from 1 instead of 0.\n",
    "    k = 1\n",
    "    while True:\n",
    "        m = 8 * k  # The number of places total in this rank, 4(2k).\n",
    "        if n < m:\n",
    "            return k, n % (2 * k)\n",
    "        n -= m  # Remove this rank's worth.\n",
    "        k += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 (1, 0)\n",
      "3 (1, 1)\n",
      "4 (1, 0)\n",
      "5 (1, 1)\n",
      "6 (1, 0)\n",
      "7 (1, 1)\n",
      "8 (1, 0)\n",
      "9 (1, 1)\n",
      "10 (2, 0)\n",
      "11 (2, 1)\n",
      "12 (2, 2)\n",
      "13 (2, 3)\n",
      "14 (2, 0)\n",
      "15 (2, 1)\n",
      "16 (2, 2)\n",
      "17 (2, 3)\n",
      "18 (2, 0)\n",
      "19 (2, 1)\n",
      "20 (2, 2)\n",
      "21 (2, 3)\n",
      "22 (2, 0)\n",
      "23 (2, 1)\n",
      "24 (2, 2)\n",
      "25 (2, 3)\n",
      "26 (3, 0)\n",
      "27 (3, 1)\n",
      "28 (3, 2)\n",
      "29 (3, 3)\n",
      "30 (3, 4)\n",
      "31 (3, 5)\n",
      "32 (3, 0)\n",
      "33 (3, 1)\n",
      "34 (3, 2)\n",
      "35 (3, 3)\n",
      "36 (3, 4)\n",
      "37 (3, 5)\n",
      "38 (3, 0)\n",
      "39 (3, 1)\n",
      "40 (3, 2)\n",
      "41 (3, 3)\n",
      "42 (3, 4)\n",
      "43 (3, 5)\n",
      "44 (3, 0)\n",
      "45 (3, 1)\n",
      "46 (3, 2)\n",
      "47 (3, 3)\n",
      "48 (3, 4)\n",
      "49 (3, 5)\n",
      "50 (4, 0)\n"
     ]
    }
   ],
   "source": [
    "for n in range(2, 51):\n",
    "    print n, rank_and_offset(n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 1\n",
      "3 2\n",
      "4 1\n",
      "5 2\n",
      "6 1\n",
      "7 2\n",
      "8 1\n",
      "9 2\n",
      "10 3\n",
      "11 2\n",
      "12 3\n",
      "13 4\n",
      "14 3\n",
      "15 2\n",
      "16 3\n",
      "17 4\n",
      "18 3\n",
      "19 2\n",
      "20 3\n",
      "21 4\n",
      "22 3\n",
      "23 2\n",
      "24 3\n",
      "25 4\n",
      "26 5\n",
      "27 4\n",
      "28 3\n",
      "29 4\n",
      "30 5\n",
      "31 6\n",
      "32 5\n",
      "33 4\n",
      "34 3\n",
      "35 4\n",
      "36 5\n",
      "37 6\n",
      "38 5\n",
      "39 4\n",
      "40 3\n",
      "41 4\n",
      "42 5\n",
      "43 6\n",
      "44 5\n",
      "45 4\n",
      "46 3\n",
      "47 4\n",
      "48 5\n",
      "49 6\n",
      "50 7\n"
     ]
    }
   ],
   "source": [
    "for n in range(2, 51):\n",
    "    k, i = rank_and_offset(n)\n",
    "    print n, row_value(k, i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Putting it all together"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def row_value(k, i):\n",
    "    return abs(i - (k - 1)) + k\n",
    "\n",
    "\n",
    "def rank_and_offset(n):\n",
    "    n -= 2  # Subtract two,\n",
    "            # one for the initial square,\n",
    "            # and one because we are counting from 1 instead of 0.\n",
    "    k = 1\n",
    "    while True:\n",
    "        m = 8 * k  # The number of places total in this rank, 4(2k).\n",
    "        if n < m:\n",
    "            return k, n % (2 * k)\n",
    "        n -= m  # Remove this rank's worth.\n",
    "        k += 1\n",
    "\n",
    "\n",
    "def aoc20173(n):\n",
    "    if n <= 1:\n",
    "        return 0\n",
    "    k, i = rank_and_offset(n)\n",
    "    return row_value(k, i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "105"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4572225"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23000000000000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sympy to the Rescue\n",
    "### Find the rank for large numbers\n",
    "Using e.g. Sympy we can find the rank directly by solving for the roots of an equation.  For large numbers this will (eventually) be faster than iterating as `rank_and_offset()` does."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy import floor, lambdify, solve, symbols\n",
    "from sympy import init_printing\n",
    "init_printing() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "k = symbols('k')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since\n",
    "\n",
    "$1 + 2 + 3 + ... + N = \\frac{N(N + 1)}{2}$\n",
    "\n",
    "and\n",
    "\n",
    "$\\sum_{n=1}^k 8n = 8(\\sum_{n=1}^k n) = 8\\frac{k(k + 1)}{2}$\n",
    "\n",
    "We want:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAHwAAAAUBAMAAAC9l0S6AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMpndu3bvImbNiRBU\nq0Qb3U6NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACAElEQVQ4EW1UzWsTQRx9NB+bzSZt6D/gHvRS\nKOZQWhAK6UHrsRShhyIW2rvBiznp0ltPxdJLDi2h9aIXc7C0emlA6k38wKKXYsA/IFZEhITG95vZ\nj5klD3bmvff7vczsMBvARsOWiSrUE26zSeD1uracGrw7Vbscqm9p99H1BWXNcNzRRZdruL7mxvi+\nDbwxtFDvE151Oec2OAz4EJt8JjrCBGd68r78YLy4pFXkltvIr9Fq7ALjfV2b49Rjr0YYBx7Q8tZs\nN19F+ZJWi/FiVdUcmQ7Dtnh1Hcd+6Ic/6vZVvFBn3PVL9yt8D58tOzj7rDut1XFgx6ky3PMRGD/t\nrPQCIMvHG+Se/IOCHd/SZvTuVL0W9y7xj0ftE+pMByj1V72AnLDj77SZuJhnd0XiN31Vy3eBsd+6\n7UWzOdts7ikhR4drQk13zAfeQuLz95akKPHM+W2hAnt1FTfdZYoPFxd/z70r50r6ZfOn3add4YQd\n/6nN2C35eCzWBgq/vEGRLBsA2zzHFhTseProeNdXpO0PyjVcSrzoA18xUWmRE3Z8SpuR69x6OS3X\n5PnwezbA8irpOPVd5G7ISRFRfPrhXgA8U17susPhUOIm5NImiOLKUTdSmOUmzcLkk0lwnFDjk7Fc\ns4NnV7e1odIfrFGKqVOLaZospo1RujHKFG/0n9V/fdOG1o/ONcUAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$4 k \\left(k + 1\\right) + 2$$"
      ],
      "text/plain": [
       "4⋅k⋅(k + 1) + 2"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "E = 2 + 8 * k * (k + 1) / 2  # For the reason for adding 2 see above.\n",
    "\n",
    "E"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can write a function to solve for $k$ given some $n$..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rank_of(n):\n",
    "    return floor(max(solve(E - n, k))) + 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First `solve()` for $E - n = 0$ which has two solutions (because the equation is quadratic so it has two roots) and since we only care about the larger one we use `max()` to select it.  It will generally not be a nice integer (unless $n$ is the number of an end-corner of a rank) so we take the `floor()` and add 1 to get the integer rank of $n$.  (Taking the `ceiling()` gives off-by-one errors on the rank boundaries.  I don't know why.  I'm basically like a monkey doing math here.)  =-D\n",
    "\n",
    "It gives correct answers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9 1\n",
      "10 2\n",
      "25 2\n",
      "26 3\n",
      "49 3\n",
      "50 4\n"
     ]
    }
   ],
   "source": [
    "for n in (9, 10, 25, 26, 49, 50):\n",
    "    print n, rank_of(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And it runs much faster (at least for large numbers):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 68 ms, sys: 8 ms, total: 76 ms\n",
      "Wall time: 73.8 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEcAAAAPBAMAAABElc8tAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABkUlEQVQoFY2QPUscURSGn4l7d4y7q6ONxGqZ\ngEbSCFZWTmfpYCHEFK6CRdIoJmQaYacNBBJJ4wcqKNhYaKNYBFeCnYKLjdhNK4j5NrKbOHlnxx+Q\nAzP33nOf+77nHCy338MKXlUxPW8cMps9QcBIMMF92HOvYRT7lg4KdzyLrHla4zi+Mas8cuDCB7PP\nU5iCRU6r1HgBkzzQZSn7gWzRTE4LairSD0sw7b0NTZ06lLHB9tp2sL/CqaD3egQVXxCyMz+U1o53\njPeR/5lCA0o0YlsvxmZYllKoRB8PpXSbQvWhz0mO5t/Que7Li0oktyjxyt01IFOPWBFDS0k/e4Hc\nYaFchXGdPnH+N4Vin14Z4epTiz5XR2UPjnVoPRm6r6kGX0LIF6EdBiVC0vSGVsj+SmvaEhTBGZYj\n0Qa0p+ndNKBcKYU0PClliuSdj7DtXDqZb5D5Lrd5hp0UGlZN0BXMvuSawh+O/ecSLgjK75oD6SXD\nzM4YdVeJ4xrN7uMQ232iGyvpeNYNoXttL9K221PiP+If4oN7f8ioQFsAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$2397916$$"
      ],
      "text/plain": [
       "2397916"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time rank_of(23000000000000)  # Compare runtime with rank_and_offset()!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 308 ms, sys: 0 ns, total: 308 ms\n",
      "Wall time: 306 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAALAAAAAUBAMAAADfFKqVAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIma7zZnddlTvRIky\nEKtZsEGBAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADLElEQVQ4Ea2VT2hcVRjFf28yfzNzZ6ZIC9LN\nQwpSXDQahCpiYzdCqWagnYUGw4h/EAo1QkMXin0b3biYqYqkwcJsrLiQBHQMMmJm46qLeUJUumlS\nQaG0UhvHWGrT6bn3PYszuBih3+Lcf+ee993zvncfeD73PBJlSd4HO488Abvb++GH9iUKx2fabczM\nt3bVRfvNTty723jVyQ4RtL8IIL/yjbY8ZHmWfUntU5gNVptehbpv3uf+cqLf79/mgu+dhuxZMdaa\nqSk1A3GR/E0c7CS7iTnEUZKBeTFmr0GiQjEk18jcoFQrNihWUsp0g8vwCxdntyX3KGMTA6oa/AZn\nIjgVsMVYhUn2wpcxOz9HukyuRvHW+CLrU6Up8r/ndbAOPViFjITHrw+ravwRXOs4+KxpeixZ256E\nehixTYNdkNyWsBbq/voEGdv7FPMHnOo44bGGZoZjOpSwA/m1yWN2/TYsBTH7EPNuS1qZmWPklPFN\nTejkHyrjphMuHV553pGG4PVQExZ+XKZ3fr5p/pTwXMxu8YijLy3jffWCfCC5KSd858O074TXD5IL\nHGsAxv/W0MLuV0LT81nw1O8ux+w9vObYxy1+3eRp3rsB6xok57KrQSS8TcoWx1CkNzThIL9o+iHP\nfa+MJRyx32XR8lMVi7mzJE6el8cn7OjBt1Yjj0s1EtafoajasQPOhFuw73MJy4qI3Y2E58ErM6Zk\nKcrtlyKNa6HLOD1FQv4MRcbmYmEHHAhelrCvl1cPYnbXWZGtsKO0HQknNzBi2HhWO/UYFfd/ZPyO\nTcWCXDgQqOr3NScFYcw+517ed/BGboL09cRpumUKOhN7ywXVrxUuyLWGe9K/oFAhU3bwgUqj3JXH\n9gM5+g97Dy25cKw9W0v41Ocyz5iDqksrfCJc8yNhrnAh0EcwELvarV9x8ADZvygumwXSgfkYx4YZ\nzqkAdDnU+KT6OLSqTT1oQRr5qoo3dbn3s+1ehVfDAeHpfn8LB+PVI9rTmu1gVt7uxGwO2096pMiO\nyIvEPNVGZSRddIP8j9AlxMOj8X8ajRaz1tTqoh8l/FFIdzk2W88X3OPQr+kOAx0PXfbg7EwAAAAA\nSUVORK5CYII=\n",
      "text/latex": [
       "$$\\left ( 2397916, \\quad 223606\\right )$$"
      ],
      "text/plain": [
       "(2397916, 223606)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time rank_and_offset(23000000000000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After finding the rank you would still have to find the actual value of the rank's first corner and subtract it (plus 2) from the number and compute the offset as above and then the final output, but this overhead is partially shared by the other method, and overshadowed by the time it (the other iterative method) would take for really big inputs.\n",
    "\n",
    "The fun thing to do here would be to graph the actual runtime of both methods against each other to find the trade-off point."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### It took me a second to realize I could do this...\n",
    "Sympy is a *symbolic* math library, and it supports symbolic manipulation of equations.  I can put in $y$ (instead of a value) and ask it to solve for $k$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "y = symbols('y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "g, f = solve(E - y, k)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The equation is quadratic so there are two roots, we are interested in the greater one..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIkAAAAqBAMAAAB1gmW6AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2ZiK7\niUTiBfEGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAB6klEQVRIDe2Uv0vDQBTHv9eiTU2pRQdxsqLo\n4CI6CEKxo5tObqKOThYHEUEUlyKIOklFwf4J4iQ42EEQt86C6Ca62IogqKh3lzQ/nkm8BEdvuL73\nve/ny/WlDfDXayoTJdFNseW1CCk/qaMIKQClaK/2/ShF+/8UYwLuuex8eS86LTdFnpleoXafPjAl\ncedDUTkw5YS6/XqSUlzoL9vWbbsMrNwUsbIsESK12qQX1jTnpfpr7V5HHcW6l+yvXXseJcOlsMG/\nSEmWgc5N6GQOIe8S51epTiFZc19JPYUJcB/QJzeQqiimtA2L1QvI/14Nek6AfCwM82jd5bXlAIy7\nsB6BDOWF0aRE6VyPfbxrqfIt/Y6JvPOokeLWvLuZMhDP8DMtiz1iUZ9L8yAwLehUAZeRU5KfQLeg\ntUr6LXIK+0DTuqDZaundnaItPa+4lZ/d6daFFHeOY8fGKZ/Mr6tBmUZWwO2dqM+r91JaRJfsZeO3\nWZRpSGTQPCvqVG1ASqO4kp+Bm0WZLv5sEi+iTr8WpPRQysvPwM2iTFesbqZgTIFuRNtUQ0HceH0c\nWoJSYVKW96lqlSEKSo2EYG0robR1+0i9olRJHXU4CcV/92eOU8WSUuPAgSLqsBFKz90U+Ush5KJU\njL/8wqcY1Dcp15UsZrvPlwAAAABJRU5ErkJggg==\n",
      "text/latex": [
       "$$- \\frac{1}{2} \\sqrt{y - 1} - \\frac{1}{2}$$"
      ],
      "text/plain": [
       "    _______    \n",
       "  ╲╱ y - 1    1\n",
       "- ───────── - ─\n",
       "      2       2"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAHgAAAAqBAMAAACKDIIdAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAVO8Qq5l2zWYiuzKJ\nRN0MreaOAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAB9ElEQVRIDe2Vu0vDUBTGvzRNSrSNILgX3TVD\nwU2LD3DRVqgIOthF0akdXETQbi4OVXDQoTg46aCLexedCvY/aEHBRVQQfOCj3nOrmCa3ubGuHmjP\nyXe+3z1tb24K/C06rVZ4pYdR6miiFTiWeuAjM63A0P/h322Y8AfTauK4d6wthPccpmaXQni8mduh\ni2Aj6zA1u6zDqb7l3I9DK//UXpU29DTm6ve7lF8Ik0Kvv4OnVgWw34MXzglgwN/BGxCyPuFF9nSY\nT2PbalzE3+QqEFaiyDSy8sk0TE8DW1oWhz5hfgzugUKRASZ7WYE0HllW125ZXJ+w8mtyPwm3qyR0\ncIwqishGlL1vUlnJt79StoXsOyvPzHxJwDT0KGVbyGD0AkqRgAO0xSnbQgpnygjxHZpBJWcDqZTC\ng/vo4kzsfC7fCDcePHtvZ+aIX2ovWPnSp+19cW1MHbJ9UOO4KJPBeIvEKQez6jtl74ghzFxBC4Eo\nNx6H+Kc1c21pb5C6w0A3EKgiWN/WyghnIguzcpb2JnGC0MM3bDpvDa811i2CWZj1Pzx938vt7t1Z\npFWK7o5cibxxz5XcKXCYcRK1pKAll6a4ZV5uFDh0PlJJYlfQlEldMPLAKbAkc7r77UnoeRg3pVTV\n3ZQphdLZBBBiD5QW4PVa7QOfZ0qXehvwRMIAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$\\frac{1}{2} \\sqrt{y - 1} - \\frac{1}{2}$$"
      ],
      "text/plain": [
       "  _______    \n",
       "╲╱ y - 1    1\n",
       "───────── - ─\n",
       "    2       2"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can take the `floor()`, add 1, and `lambdify()` the equation to get a Python function that calculates the rank directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAK0AAAAqBAMAAAAzNMYQAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEGYiq+/dVJl2zbsy\niUT7WiApAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACUUlEQVRIDe2Uv2/TQBTHv1YgsdMmRCUwdCEz\nElIHCANLqAAx0TLASpEgAwxMSGXrUImqVCJigimRqBgipHZg60D+BEZAQup/EH5ISCBKuPfsc8/2\nw2fHYuOk5L177/v9+Hw+G/ino3J9GrzV1Vz/MgU3g8ubhgu7y66Q7sfusiv+c6Ud8Gv23Ysq3Ik8\nPscuEXXFmjyNKi5IEqEWdQmC2Em8JkmEWhp3jvURRWkgMKRS4PKk3lkqupd/Lh423f3DPC3Trqok\nYm60MR+dWmdZuY9F0sOGWFbFBJekyfU6KwLAubpk5T7yfb40ya21BC7Qz8r1pUnuSRFbnPsMcJ73\ncC62vsLrXQFqlWX0Y8suwqUlej3gvDvAXnHuMf7MAO13ilVWv8bRHn6o6LzqqnFvpNJgf+ep0H1N\nBe3yz9nH4fDucLhNDZYaz61+elkVz1BnvDD7i6IxCuxD5avi3CbWJjy6hjkKcHETqNBe4A1mOiZU\n5UW4/X1UG8R7gnGLojGKcE/tYpVRzQ9PFwymStdvbbeilXCmvw/Be+xL+bmVNvZGJHO/4WUg3wxi\nStCuOJctzG2i9ptmpYN6h+KRgcNzyv8+tEtzj5tS5l4EbnDxbZVvv9ya6ZkiOdcuzY2omKvOwdKI\nyuNL3Ky/2OKY/qddIvdE9w6w0wi45fjbkEb2Xe3u/TTRAz5f3m6aJtnzXcl6WKkfhGmOxO4qd3Lg\nQqndtRFq8yRWl7eWB6e1dtcqSnxwtSNbtLpm1+Dl59pd7U/vr2Rboqmyu3Ymk++mI1ue5voDRu6s\n5n/E50UAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$\\lfloor{\\frac{1}{2} \\sqrt{y - 1} - \\frac{1}{2}}\\rfloor + 1$$"
      ],
      "text/plain": [
       "⎢  _______    ⎥    \n",
       "⎢╲╱ y - 1    1⎥    \n",
       "⎢───────── - ─⎥ + 1\n",
       "⎣    2       2⎦    "
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "floor(f) + 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "F = lambdify(y, floor(f) + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9 1\n",
      "10 2\n",
      "25 2\n",
      "26 3\n",
      "49 3\n",
      "50 4\n"
     ]
    }
   ],
   "source": [
    "for n in (9, 10, 25, 26, 49, 50):\n",
    "    print n, int(F(n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's pretty fast."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 0 ns, sys: 0 ns, total: 0 ns\n",
      "Wall time: 11.9 µs\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEcAAAAPBAMAAABElc8tAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABkUlEQVQoFY2QPUscURSGn4l7d4y7q6ONxGqZ\ngEbSCFZWTmfpYCHEFK6CRdIoJmQaYacNBBJJ4wcqKNhYaKNYBFeCnYKLjdhNK4j5NrKbOHlnxx+Q\nAzP33nOf+77nHCy338MKXlUxPW8cMps9QcBIMMF92HOvYRT7lg4KdzyLrHla4zi+Mas8cuDCB7PP\nU5iCRU6r1HgBkzzQZSn7gWzRTE4LairSD0sw7b0NTZ06lLHB9tp2sL/CqaD3egQVXxCyMz+U1o53\njPeR/5lCA0o0YlsvxmZYllKoRB8PpXSbQvWhz0mO5t/Que7Li0oktyjxyt01IFOPWBFDS0k/e4Hc\nYaFchXGdPnH+N4Vin14Z4epTiz5XR2UPjnVoPRm6r6kGX0LIF6EdBiVC0vSGVsj+SmvaEhTBGZYj\n0Qa0p+ndNKBcKYU0PClliuSdj7DtXDqZb5D5Lrd5hp0UGlZN0BXMvuSawh+O/ecSLgjK75oD6SXD\nzM4YdVeJ4xrN7uMQ232iGyvpeNYNoXttL9K221PiP+If4oN7f8ioQFsAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$2397916$$"
      ],
      "text/plain": [
       "2397916"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time int(F(23000000000000))  # The clear winner."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Knowing the equation we could write our own function manually, but the speed is no better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import floor as mfloor, sqrt\n",
    "\n",
    "def mrank_of(n):\n",
    "    return int(mfloor(sqrt(23000000000000 - 1) / 2 - 0.5) + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 0 ns, sys: 0 ns, total: 0 ns\n",
      "Wall time: 12.9 µs\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEcAAAAPBAMAAABElc8tAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABkUlEQVQoFY2QPUscURSGn4l7d4y7q6ONxGqZ\ngEbSCFZWTmfpYCHEFK6CRdIoJmQaYacNBBJJ4wcqKNhYaKNYBFeCnYKLjdhNK4j5NrKbOHlnxx+Q\nAzP33nOf+77nHCy338MKXlUxPW8cMps9QcBIMMF92HOvYRT7lg4KdzyLrHla4zi+Mas8cuDCB7PP\nU5iCRU6r1HgBkzzQZSn7gWzRTE4LairSD0sw7b0NTZ06lLHB9tp2sL/CqaD3egQVXxCyMz+U1o53\njPeR/5lCA0o0YlsvxmZYllKoRB8PpXSbQvWhz0mO5t/Que7Li0oktyjxyt01IFOPWBFDS0k/e4Hc\nYaFchXGdPnH+N4Vin14Z4epTiz5XR2UPjnVoPRm6r6kGX0LIF6EdBiVC0vSGVsj+SmvaEhTBGZYj\n0Qa0p+ndNKBcKYU0PClliuSdj7DtXDqZb5D5Lrd5hp0UGlZN0BXMvuSawh+O/ecSLgjK75oD6SXD\nzM4YdVeJ4xrN7uMQ232iGyvpeNYNoXttL9K221PiP+If4oN7f8ioQFsAAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$2397916$$"
      ],
      "text/plain": [
       "2397916"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time mrank_of(23000000000000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Given $n$ and a rank, compute the offset.\n",
    "\n",
    "Now that we have a fast way to get the rank, we still need to use it to compute the offset into a pyramid row."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "def offset_of(n, k):\n",
    "    return (n - 2 + 4 * k * (k - 1)) % (2 * k)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(Note the sneaky way the sign changes from $k(k + 1)$ to $k(k - 1)$.  This is because we want to subract the $(k - 1)$th rank's total places (its own and those of lesser rank) from our $n$ of rank $k$.  Substituting $k - 1$ for $k$ in $k(k + 1)$ gives $(k - 1)(k - 1 + 1)$, which of course simplifies to $k(k - 1)$.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAADsAAAAOBAMAAABjvHmeAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABIElEQVQYGTWQoU8DMRSHvwuULWNLDgwJ6jIS\nCJlcQoLaOeSKQaAwCDAsg2WCiTMI1AQIRjIBFoHFjSCwNPwDmyMYSBBAdoTjtR2iX76+X/r6WoJy\nNcajfWgg1zlCrbzE3tgi9+0xT+kXdUeFWaOuvLELPY8nw5ipiCqvcOyNSziIHU4TldINgTUYamcM\ntMQO2ObrkvIJXePM7m71BNsN0o2HRH1IfG/NpvmvCRautUpH9AMp1FvWbFzY+UfuQmWa1U05XW9Z\ns23Lsjzo6TG8n7jm1hIoRpJazEHN3EhxJKMNvcEzQegg3Wpmz56pCrQzpiOKocOZvCGsy432Wyo4\nY7Hd3Pd4o/TDTEP1KRh17o1Blo098uUlGaW5HKM6j7G3P7xTb/ft54xWAAAAAElFTkSuQmCC\n",
      "text/latex": [
       "$$223606$$"
      ],
      "text/plain": [
       "223606"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "offset_of(23000000000000, 2397916)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, we can compute the rank, then the offset, then the row value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rank_of(n):\n",
    "    return int(mfloor(sqrt(n - 1) / 2 - 0.5) + 1)\n",
    "\n",
    "\n",
    "def offset_of(n, k):\n",
    "    return (n - 2 + 4 * k * (k - 1)) % (2 * k)\n",
    "\n",
    "\n",
    "def row_value(k, i):\n",
    "    return abs(i - (k - 1)) + k\n",
    "\n",
    "\n",
    "def aoc20173(n):\n",
    "    k = rank_of(n)\n",
    "    i = offset_of(n, k)\n",
    "    return row_value(k, i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAkAAAAOBAMAAAAPuiubAAAALVBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAOrOgAAAADnRSTlMAIpm7MhCriUTv3c12VLge\nopIAAAAJcEhZcwAADsQAAA7EAZUrDhsAAABOSURBVAgdY2BUMnZgYAhjYH/BwJDKwDCTgWEWA0Oe\nA8O+ABAJBOsCgATHcxCTKwFEKoEIHgUQeYmBUYCBRYGBR4BBqrwoi4Fh37t3rxgAK5QOlzv7snYA\nAAAASUVORK5CYII=\n",
      "text/latex": [
       "$$2$$"
      ],
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAB0AAAAPBAMAAADqo9msAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAVO8Qq5l2zWaJMt0i\nu0SCRuA9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAArElEQVQIHWNgAAHmyM4FDOzJXIFANqMyAwO7\nAPMeBqb//ycwMJiEfGZgaGJgmM7APiUHpJYNyL/CwCBvwALiQfhfGBjeCyD4zF+B/ASWjtQFEHme\nnwwM6yfwGvD8g/KB8uuBZjPchvAh6oHs+ANw8+QF3BkY5j+A8O8yMPQbqAPlDSB8oHvCGQIYGLZD\n9DNwCzBrMRxl4NBhYGB1+u7BwDwtZQEDT6QrUDkaAADf+TCFzC1FdQAAAABJRU5ErkJggg==\n",
      "text/latex": [
       "$$105$$"
      ],
      "text/plain": [
       "105"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEgAAAAPBAMAAAC1npSgAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMpndu3bvImbNiRBU\nq0Qb3U6NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABGklEQVQoFYWQsUrDUBRAT6I1pVYJ/YLYURcH\nV9HBzS9wtjgJPnRx00XnDLq4tIhTQOjiIojiLghSKEjRxR9QUajU5715hfc2Qzi83HMgjwvQgNNu\n4y5ani8KkuZaGqA00rAEO3ZI1Vo74obab4DSSFNpwVnPEBt45Bm2ApRGov0TlVCTN2UTXlKP0ojs\njCM5vkG7K5HHOKoaifpHc9KwqmClG8CZKyRa5+BV/nYoltlhCGc6GsHkItzqgQm9oIeaeuqi+Bs2\nyqip9EDMNRLN5LodXZhsJAvhzMNg8NWbyol/mB5pdE9iPJyRcYtYLpETvctHlFExHs7I/JMk49hQ\n12ivOH8K4Axc2D67lwuQbEvUtvYjgDMy//f5A0ICeXTNG40LAAAAAElFTkSuQmCC\n",
      "text/latex": [
       "$$4572225$$"
      ],
      "text/plain": [
       "4572225"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "aoc20173(23000000000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 0 ns, sys: 0 ns, total: 0 ns\n",
      "Wall time: 20 µs\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIUAAAAPBAMAAAA43xGxAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACa0lEQVQoFaXTT0gUYRjH8e/+mZ11d50duhWE\nw9JfvAxJQaeGIDw6eCjMg1uUUUQuInpIci6dXaGCCsvOEe2hfwfTJaKIhLYIOrqeQhLUcl3RdHve\neTfo3h6GnefzPj/e99l3ieQ6PDBHhzAODtvy+C6v3TeGgJH3HpqJO5qZ9k9W6B451+Swh9OYGxiv\naKenGpkgXTEewWvO2vQG0ZJmSLmaedioYzxgd5PDHi7CXWIOHVyG8yzCdawiZokjxFzN8MHVzMur\nNokiCUdz2MM9GPDGbdnbFoxxDOb9WJ7WWnJVapqJ/HA1k5datoS5ojnsYdaXjOMixi/45K3DeCWb\nJ7kdK0pRM2ba1Rxm9Llk1kJuFmXdU3+r803AfdnHzZ+SUe5zSP7OPhs9pFKEWUi7IQdcW9pHi+xj\nQ7PqCWRNsm5sVZmUgzC7UIeuQluBeL1vhpZKyBhlyVBc5ShtgblCekezLsrM80bD57CfLreOfZZ9\nSIajMmpEb0tGKo+JZChWmbEppvm2rflvMQebsByw9Hbs1D9nmcLakB7hrypDsSfv0VWsuc61rGZd\nzDjwWDKq4gO+zHRezbR1O1XC2gFhoxBmKE6oUcjCRK3JqghfiNjyM8s+4IVcE5Z9uRdWTW6B2ofw\n3v7+gTvlkGWc0Zp8S+ebrHrULc7YXTIPFu34qrpj7VhFoqW4zKOoGVpczVGZT8maoMvWHPawZ2Tw\nComCMclHv7dKqmLcgif0eFyip6JZrpWrOeJIVua5MYPmsIfZRkMmOnjAw8zJfTBG33lwZu6C/A9z\n8tBsnlivhsyu4f2yOhc0WRflcP/7+QN1gvGXxRfSRAAAAABJRU5ErkJggg==\n",
      "text/latex": [
       "$$2690062495969$$"
      ],
      "text/plain": [
       "2690062495969"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time aoc20173(23000000000000000000000000)  # Fast for large values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A Joy Version\n",
    "At this point I feel confident that I can implement a concise version of this code in Joy.  ;-)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "from notebook_preamble import J, V, define"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `rank_of`\n",
    "\n",
    "       n rank_of\n",
    "    ---------------\n",
    "          k\n",
    "\n",
    "The translation is straightforward.\n",
    "\n",
    "    int(floor(sqrt(n - 1) / 2 - 0.5) + 1)\n",
    "\n",
    "    rank_of == -- sqrt 2 / 0.5 - floor ++"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "define('rank_of == -- sqrt 2 / 0.5 - floor ++')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `offset_of`\n",
    "\n",
    "       n k offset_of\n",
    "    -------------------\n",
    "             i\n",
    "\n",
    "    (n - 2 + 4 * k * (k - 1)) % (2 * k)\n",
    "\n",
    "A little tricky...\n",
    "\n",
    "    n k dup 2 *\n",
    "    n k k 2 *\n",
    "    n k k*2 [Q] dip %\n",
    "    n k Q k*2 %\n",
    "\n",
    "    n k dup --\n",
    "    n k k --\n",
    "    n k k-1 4 * * 2 + -\n",
    "    n k*k-1*4     2 + -\n",
    "    n k*k-1*4+2       -\n",
    "    n-k*k-1*4+2\n",
    "\n",
    "    n-k*k-1*4+2 k*2 %\n",
    "    n-k*k-1*4+2%k*2\n",
    "\n",
    "Ergo:\n",
    "\n",
    "    offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "define('offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `row_value`\n",
    "\n",
    "       k i row_value\n",
    "    -------------------\n",
    "            n\n",
    "\n",
    "    abs(i - (k - 1)) + k\n",
    "\n",
    "    k i over -- - abs +\n",
    "    k i k    -- - abs +\n",
    "    k i k-1     - abs +\n",
    "    k i-k-1       abs +\n",
    "    k |i-k-1|         +\n",
    "    k+|i-k-1|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "define('row_value == over -- - abs +')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `aoc2017.3`\n",
    "\n",
    "       n aoc2017.3\n",
    "    -----------------\n",
    "            m\n",
    "\n",
    "    n dup rank_of\n",
    "    n k [offset_of] dupdip\n",
    "    n k offset_of k\n",
    "    i             k swap row_value\n",
    "    k i row_value\n",
    "    m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "define('aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "J('23 aoc2017.3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "105\n"
     ]
    }
   ],
   "source": [
    "J('23000 aoc2017.3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                    . 23000000000000 aoc2017.3\n",
      "                                     23000000000000 . aoc2017.3\n",
      "                                     23000000000000 . dup rank_of [offset_of] dupdip swap row_value\n",
      "                      23000000000000 23000000000000 . rank_of [offset_of] dupdip swap row_value\n",
      "                      23000000000000 23000000000000 . -- sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value\n",
      "                      23000000000000 22999999999999 . sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value\n",
      "                   23000000000000 4795831.523312615 . 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value\n",
      "                 23000000000000 4795831.523312615 2 . / 0.5 - floor ++ [offset_of] dupdip swap row_value\n",
      "                  23000000000000 2397915.7616563076 . 0.5 - floor ++ [offset_of] dupdip swap row_value\n",
      "              23000000000000 2397915.7616563076 0.5 . - floor ++ [offset_of] dupdip swap row_value\n",
      "                  23000000000000 2397915.2616563076 . floor ++ [offset_of] dupdip swap row_value\n",
      "                             23000000000000 2397915 . ++ [offset_of] dupdip swap row_value\n",
      "                             23000000000000 2397916 . [offset_of] dupdip swap row_value\n",
      "                 23000000000000 2397916 [offset_of] . dupdip swap row_value\n",
      "                             23000000000000 2397916 . offset_of 2397916 swap row_value\n",
      "                             23000000000000 2397916 . dup 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value\n",
      "                     23000000000000 2397916 2397916 . 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value\n",
      "                   23000000000000 2397916 2397916 2 . * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value\n",
      "                     23000000000000 2397916 4795832 . [dup -- 4 * * 2 + -] dip % 2397916 swap row_value\n",
      "23000000000000 2397916 4795832 [dup -- 4 * * 2 + -] . dip % 2397916 swap row_value\n",
      "                             23000000000000 2397916 . dup -- 4 * * 2 + - 4795832 % 2397916 swap row_value\n",
      "                     23000000000000 2397916 2397916 . -- 4 * * 2 + - 4795832 % 2397916 swap row_value\n",
      "                     23000000000000 2397916 2397915 . 4 * * 2 + - 4795832 % 2397916 swap row_value\n",
      "                   23000000000000 2397916 2397915 4 . * * 2 + - 4795832 % 2397916 swap row_value\n",
      "                     23000000000000 2397916 9591660 . * 2 + - 4795832 % 2397916 swap row_value\n",
      "                      23000000000000 22999994980560 . 2 + - 4795832 % 2397916 swap row_value\n",
      "                    23000000000000 22999994980560 2 . + - 4795832 % 2397916 swap row_value\n",
      "                      23000000000000 22999994980562 . - 4795832 % 2397916 swap row_value\n",
      "                                            5019438 . 4795832 % 2397916 swap row_value\n",
      "                                    5019438 4795832 . % 2397916 swap row_value\n",
      "                                             223606 . 2397916 swap row_value\n",
      "                                     223606 2397916 . swap row_value\n",
      "                                     2397916 223606 . row_value\n",
      "                                     2397916 223606 . over -- - abs +\n",
      "                             2397916 223606 2397916 . -- - abs +\n",
      "                             2397916 223606 2397915 . - abs +\n",
      "                                   2397916 -2174309 . abs +\n",
      "                                    2397916 2174309 . +\n",
      "                                            4572225 . \n"
     ]
    }
   ],
   "source": [
    "V('23000000000000 aoc2017.3')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "      rank_of == -- sqrt 2 / 0.5 - floor ++\n",
    "    offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %\n",
    "    row_value == over -- - abs +\n",
    "\n",
    "    aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
