2019-07-16 23:09:53 +00:00
|
|
|
|
"""
|
2020-10-09 03:16:55 +00:00
|
|
|
|
Problem 15: https://projecteuler.net/problem=15
|
|
|
|
|
|
2019-07-16 23:09:53 +00:00
|
|
|
|
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.
|
|
|
|
|
How many such routes are there through a 20×20 grid?
|
|
|
|
|
"""
|
2024-03-13 06:52:41 +00:00
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
|
from math import factorial
|
|
|
|
|
|
2019-07-16 23:09:53 +00:00
|
|
|
|
|
2020-10-09 03:16:55 +00:00
|
|
|
|
def solution(n: int = 20) -> int:
|
2019-07-16 23:09:53 +00:00
|
|
|
|
"""
|
2020-10-09 03:16:55 +00:00
|
|
|
|
Returns the number of paths possible in a n x n grid starting at top left
|
|
|
|
|
corner going to bottom right corner and being able to move right and down
|
|
|
|
|
only.
|
|
|
|
|
>>> solution(25)
|
|
|
|
|
126410606437752
|
|
|
|
|
>>> solution(23)
|
|
|
|
|
8233430727600
|
|
|
|
|
>>> solution(20)
|
|
|
|
|
137846528820
|
|
|
|
|
>>> solution(15)
|
|
|
|
|
155117520
|
|
|
|
|
>>> solution(1)
|
|
|
|
|
2
|
2019-07-16 23:09:53 +00:00
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
|
2019-07-16 23:09:53 +00:00
|
|
|
|
# 2, 3,...
|
2021-10-21 07:06:32 +00:00
|
|
|
|
k = n // 2
|
2019-07-16 23:09:53 +00:00
|
|
|
|
|
|
|
|
|
return int(factorial(n) / (factorial(k) * factorial(n - k)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
if len(sys.argv) == 1:
|
2020-10-09 03:16:55 +00:00
|
|
|
|
print(solution(20))
|
2019-07-16 23:09:53 +00:00
|
|
|
|
else:
|
|
|
|
|
try:
|
|
|
|
|
n = int(sys.argv[1])
|
2020-10-09 03:16:55 +00:00
|
|
|
|
print(solution(n))
|
2019-07-16 23:09:53 +00:00
|
|
|
|
except ValueError:
|
|
|
|
|
print("Invalid entry - please enter a number.")
|