solution.scm 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ;;; Lattice paths
  2. ;;; Problem 15
  3. ;;; Starting in the top left corner of a 2×2 grid, and only
  4. ;;; being able to move to the right and down, there are
  5. ;;; exactly 6 routes to the bottom right corner.
  6. ;;; How many such routes are there through a 20×20 grid?
  7. ;;; NOTE: This puzzle means to state, that the top left
  8. ;;; corner is on the LINES, that make the grid, not the top
  9. ;;; left SQUARE of the grid!
  10. (import
  11. (except (rnrs base) let-values map)
  12. (only (guile)
  13. lambda* λ
  14. ;; printing
  15. display
  16. simple-format)
  17. (lib math))
  18. (define count-paths
  19. (λ (grid-size)
  20. (let* (;; Half of the steps need to be to the right and
  21. ;; half of them downwards.
  22. [steps-one-direction (- grid-size 1)]
  23. ;; We need twice the (grid-size - 1) steps to get
  24. ;; from one corner to the other.
  25. [steps (* (- grid-size 1) 2)])
  26. (/
  27. (/
  28. ;; STEP 1: The first part is the number of ways to
  29. ;; pick positions for going into one direction (for
  30. ;; example towards the right). The first pick has a
  31. ;; choice of n positions, the second one has n-1
  32. ;; positions available, the third one n-2 and so on,
  33. ;; until all steps are taken.
  34. (factorial steps)
  35. ;; STEP 2: However, we only need to look at half
  36. ;; the steps being taken into a single direction
  37. ;; and their positions. All other steps will
  38. ;; automatically be towards the other
  39. ;; direction. This means, that (factorial steps) is
  40. ;; too large. To take away the part of the term,
  41. ;; which is too much, we need to devide by
  42. ;; (factorial steps-one-direction).
  43. (factorial steps-one-direction))
  44. ;; STEP 3: However, since all steps into one
  45. ;; direction are actually identical direction values,
  46. ;; whose order does not matter, we need to divide by
  47. ;; the factor of duplicates, that were introduced by
  48. ;; taking the factorial.
  49. (factorial steps-one-direction)))))
  50. (let ([grid-size 21])
  51. (display
  52. (simple-format
  53. #f "possible paths: ~a\n"
  54. (count-paths grid-size))))