{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Euler Problem 15\n", "\n", "Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.\n", "\n", "![problem picture](https://projecteuler.net/project/images/p015.gif)\n", "\n", "\n", "How many such routes are there through a 20×20 grid?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We should be able to get this with some thinking. Every move for a $nxn$ grid has to contain n downward and n rightward moves. So in total there are 2n moves. Now we only have to get all permutations available with 2n moves. Normally, we would calculate the factorial, but this only works if all symbols are different. In this case we always only have two symbols for the 2n moves.\n", "For each solution there exist a certain number of ways we can create this solution. Let's assume we have two right arrows called (1, 2) and two down arrows called (3, 4). We now have the following options to generate the solution in the upper left corner.\n", "\n", "~~~\n", "1 2 3 4\n", "1 2 4 3\n", "2 1 3 4\n", "2 1 4 2\n", "~~~\n", "\n", "So this means if we calculate the number of ways using the factorial $(2\\times2)! = 4! = 24$, four of the solutions are equal which gives us $\\frac{24}{4} = 6$. The way to calculate the four should be $2! \\times 2! = 4$, so our formula is $\\frac{(2\\times n)!}{n! \\times n!}$. So let's try that." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "137846528820\n" ] } ], "source": [ "def get_number_of_routes(n):\n", " from math import factorial\n", " return factorial(2 * n) // (factorial(n) * factorial(n))\n", "\n", "assert(get_number_of_routes(2) == 6)\n", "assert(get_number_of_routes(20) == 137846528820)\n", "print(get_number_of_routes(20))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Would actually be interesting to see how this formular changes if we add another dimension. The number of moves would change to $3n$ obviously. And I think the number of permutations changes to remove changes to $n! \\times n! \\times n! = (n!)^3$.\n", "\n", "So the final formula is\n", "\n", "$n_{routes} = \\frac{(d \\times n)!}{(n!)^d}$\n", "\n", "where d is the number of dimensions and n is the size of the grid." ] } ], "metadata": { "completion_date": "Sun, 31 Aug 2014, 20:05", "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": [ "factorial", "grid" ] }, "nbformat": 4, "nbformat_minor": 0 }