{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Euler Problem 67\n",
    "\n",
    "By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n",
    "\n",
    "~~~\n",
    "   3\n",
    "  7 4\n",
    " 2 4 6\n",
    "8 5 9 3\n",
    "~~~\n",
    "\n",
    "That is, 3 + 7 + 4 + 9 = 23.\n",
    "\n",
    "Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.\n",
    "\n",
    "NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So let's hope our solution is good. I have saved the triangle in a file EulerProblem067.txt in the same directory as this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7273\n"
     ]
    }
   ],
   "source": [
    "def find_greatest_path_sum_in_triangle_string(ts):\n",
    "    from functools import reduce\n",
    "    xss = [list(map(int, xs.split())) for xs in ts.split(\"\\n\") if xs]\n",
    "    xss.reverse()\n",
    "    r = lambda xs, ys: [max([xs[i] + ys[i], xs[i + 1] + ys[i]]) for i in range(len(ys))]\n",
    "    return reduce(r, xss[1:], xss[0])[0]\n",
    "\n",
    "with open('EulerProblem067.txt', 'r') as f:\n",
    "    triangle_string = f.read()\n",
    "    \n",
    "print(find_greatest_path_sum_in_triangle_string(triangle_string))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Well, that was fast."
   ]
  }
 ],
 "metadata": {
  "completion_date": "Fri, 5 Sep 2014, 07:36",
  "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.5.4"
  },
  "tags": [
   "reduce",
   "triangle"
  ]
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
