{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Advent of Code 2017\n",
    "\n",
    "## December 5th\n",
    "...a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.\n",
    "\n",
    "In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered.\n",
    "\n",
    "For example, consider the following list of jump offsets:\n",
    "\n",
    "    0\n",
    "    3\n",
    "    0\n",
    "    1\n",
    "    -3\n",
    "\n",
    "Positive jumps (\"forward\") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:\n",
    "\n",
    "*    (0) 3  0  1  -3  - before we have taken any steps.\n",
    "*    (1) 3  0  1  -3  - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.\n",
    "*     2 (3) 0  1  -3  - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.\n",
    "*     2  4  0  1 (-3) - jump all the way to the end; leave a 4 behind.\n",
    "*     2 (4) 0  1  -2  - go back to where we just were; increment -3 to -2.\n",
    "*     2  5  0  1  -2  - jump 4 steps forward, escaping the maze.\n",
    "\n",
    "In this example, the exit is reached in 5 steps.\n",
    "\n",
    "How many steps does it take to reach the exit?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Breakdown\n",
    "For now, I'm going to assume a starting state with the size of the sequence pre-computed.  We need it to define the exit condition and it is a trivial preamble to generate it.  We then need and `index` and a `step-count`, which are both initially zero.  Then we have the sequence itself, and some recursive function `F` that does the work.\n",
    "\n",
    "       size index step-count [...] F\n",
    "    -----------------------------------\n",
    "                step-count\n",
    "\n",
    "    F == [P] [T] [R1] [R2] genrec\n",
    "\n",
    "Later on I was thinking about it and the Forth heuristic came to mind, to wit: four things on the stack are kind of much.  Immediately I realized that the size properly belongs in the predicate of `F`!  D'oh!\n",
    "\n",
    "       index step-count [...] F\n",
    "    ------------------------------\n",
    "             step-count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, let's start by nailing down the predicate:\n",
    "\n",
    "    F == [P] [T] [R1]   [R2] genrec\n",
    "      == [P] [T] [R1 [F] R2] ifte\n",
    "\n",
    "    0 0 [0 3 0 1 -3] popop 5 >=\n",
    "\n",
    "    P == popop 5 >="
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we need the else-part:\n",
    "\n",
    "    index step-count [0 3 0 1 -3] roll< popop\n",
    "\n",
    "    E == roll< popop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Last but not least, the recursive branch\n",
    "\n",
    "    0 0 [0 3 0 1 -3] R1 [F] R2\n",
    "\n",
    "The `R1` function has a big job:\n",
    "\n",
    "    R1 == get the value at index\n",
    "          increment the value at the index\n",
    "          add the value gotten to the index\n",
    "          increment the step count\n",
    "\n",
    "The only tricky thing there is incrementing an integer in the sequence.  Joy sequences are not particularly good for random access.  We could encode the list of jump offsets in a big integer and use math to do the processing for a good speed-up, but it still wouldn't beat the performance of e.g. a mutable array.  This is just one of those places where \"plain vanilla\" Joypy doesn't shine (in default performance.  The legendary *Sufficiently-Smart Compiler* would of course rewrite this function to use an array \"under the hood\".)\n",
    "\n",
    "In the meantime, I'm going to write a primitive function that just does what we need."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from notebook_preamble import D, J, V, define\n",
    "from joy.library import SimpleFunctionWrapper\n",
    "from joy.utils.stack import list_to_stack\n",
    "\n",
    "\n",
    "@SimpleFunctionWrapper\n",
    "def incr_at(stack):\n",
    "    '''Given a index and a sequence of integers, increment the integer at the index.\n",
    "\n",
    "    E.g.:\n",
    "\n",
    "       3 [0 1 2 3 4 5] incr_at\n",
    "    -----------------------------\n",
    "         [0 1 2 4 4 5]\n",
    "    \n",
    "    '''\n",
    "    sequence, (i, stack) = stack\n",
    "    mem = []\n",
    "    while i >= 0:\n",
    "        term, sequence = sequence\n",
    "        mem.append(term)\n",
    "        i -= 1\n",
    "    mem[-1] += 1\n",
    "    return list_to_stack(mem, sequence), stack\n",
    "\n",
    "\n",
    "D['incr_at'] = incr_at"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 4 4 5]\n"
     ]
    }
   ],
   "source": [
    "J('3 [0 1 2 3 4 5] incr_at')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### get the value at index\n",
    "\n",
    "    3 0 [0 1 2 3 4] [roll< at] nullary\n",
    "    3 0 [0 1 2 n 4] n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### increment the value at the index\n",
    "\n",
    "    3 0 [0 1 2 n 4] n [Q] dip\n",
    "    3 0 [0 1 2 n 4] Q n\n",
    "    3 0 [0 1 2 n 4] [popd incr_at] unary n\n",
    "    3 0 [0 1 2 n+1 4] n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### add the value gotten to the index\n",
    "\n",
    "    3 0 [0 1 2 n+1 4] n [+] cons dipd\n",
    "    3 0 [0 1 2 n+1 4] [n +]      dipd\n",
    "    3 n + 0 [0 1 2 n+1 4]\n",
    "    3+n   0 [0 1 2 n+1 4]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### increment the step count\n",
    "\n",
    "    3+n 0 [0 1 2 n+1 4] [++] dip\n",
    "    3+n 1 [0 1 2 n+1 4]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### All together now...\n",
    "\n",
    "    get_value == [roll< at] nullary\n",
    "    incr_value == [[popd incr_at] unary] dip\n",
    "    add_value == [+] cons dipd\n",
    "    incr_step_count == [++] dip\n",
    "\n",
    "    R1 == get_value incr_value add_value incr_step_count\n",
    "\n",
    "    F == [P] [T] [R1] primrec\n",
    "    \n",
    "    F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] tailrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from joy.library import DefinitionWrapper\n",
    "\n",
    "\n",
    "DefinitionWrapper.add_definitions('''\n",
    "\n",
    "      get_value [roll< at] nullary\n",
    "     incr_value [[popd incr_at] unary] dip\n",
    "      add_value [+] cons dipd\n",
    "incr_step_count [++] dip\n",
    "\n",
    "     AoC2017.5.0 get_value incr_value add_value incr_step_count\n",
    "\n",
    "''', D)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from joy.library import DefinitionWrapper\n",
    "\n",
    "\n",
    "DefinitionWrapper.add_definitions('''\n",
    "\n",
    "      get_value [roll< at] nullary\n",
    "     incr_value [[popd incr_at] unary] dip\n",
    "      add_value [+] cons dipd\n",
    "incr_step_count [++] dip\n",
    "\n",
    "     AoC2017.5.0 get_value incr_value add_value incr_step_count\n",
    "\n",
    "''', D)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "define('F [popop 5 >=] [roll< popop] [AoC2017.5.0] tailrec')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "J('0 0 [0 3 0 1 -3] F')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preamble for setting up predicate, `index`, and `step-count`\n",
    "\n",
    "We want to go from this to this:\n",
    "\n",
    "       [...] AoC2017.5.preamble\n",
    "    ------------------------------\n",
    "        0 0 [...] [popop n >=]\n",
    "\n",
    "Where `n` is the size of the sequence.\n",
    "\n",
    "The first part is obviously `0 0 roll<`, then `dup size`:\n",
    "\n",
    "    [...] 0 0 roll< dup size\n",
    "    0 0 [...] n\n",
    "\n",
    "Then:\n",
    "\n",
    "    0 0 [...] n [>=] cons [popop] swoncat\n",
    "\n",
    "So:\n",
    "\n",
    "    init-index-and-step-count == 0 0 roll<\n",
    "    prepare-predicate == dup size [>=] cons [popop] swoncat\n",
    "\n",
    "    AoC2017.5.preamble == init-index-and-step-count prepare-predicate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "DefinitionWrapper.add_definitions('''\n",
    "\n",
    "init-index-and-step-count 0 0 roll<\n",
    "prepare-predicate dup size [>=] cons [popop] swoncat\n",
    "\n",
    "AoC2017.5.preamble init-index-and-step-count prepare-predicate\n",
    "\n",
    "AoC2017.5 AoC2017.5.preamble [roll< popop] [AoC2017.5.0] tailrec\n",
    "\n",
    "''', D)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "J('[0 3 0 1 -3] AoC2017.5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "                    AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec\n",
    "\n",
    "                  AoC2017.5.0 == get_value incr_value add_value incr_step_count\n",
    "           AoC2017.5.preamble == init-index-and-step-count prepare-predicate\n",
    "\n",
    "                    get_value == [roll< at] nullary\n",
    "                   incr_value == [[popd incr_at] unary] dip\n",
    "                    add_value == [+] cons dipd\n",
    "              incr_step_count == [++] dip\n",
    "\n",
    "    init-index-and-step-count == 0 0 roll<\n",
    "            prepare-predicate == dup size [>=] cons [popop] swoncat\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is by far the largest program I have yet written in Joy.  Even with the `incr_at` function it is still a bear.  There may be an arrangement of the parameters that would permit more elegant definitions, but it still wouldn't be as efficient as something written in assembly, C, or even Python."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "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.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
