manicolosi (owner)

Revisions

gist: 173095 Download_button fork
public
Public Clone URL: git://gist.github.com/173095.git
Embed All Files: show embed
problem15.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Project Euler - Problem 15
# http://projecteuler.net/index.php?section=problems&id=15
#
# Starting in the top left corner of a 2×2 grid, there are 6 routes
# (without backtracking) to the bottom right corner.
#
# ******* ****--+ ****--+ *--+--+ *--+--+ *--+--+
# | | * | * | | * | * | | * | | * | |
# +--+--* +--**** +--*--+ ******* ****--+ *--+--+
# | | * | | * | * | | | * | * | * | |
# +--+--* +--+--* +--**** +--+--* +--**** *******
#
# How many routes are there through a 20×20 grid?
 
class Problem15
  def solve
    count_paths [0, 0], 20
  end
 
  def count_paths(start, size)
    sx, sy = *start
 
    return 1 if sx == size || sy == size
 
    count_paths_cached([sx + 1, sy], size) +
    count_paths_cached([sx, sy + 1], size)
  end
 
  def count_paths_cached(start, dest)
    @cache ||= {}
 
    unless @cache.has_key? start
      @cache[start] = count_paths(start, dest)
    end
 
    @cache[start]
  end
end
 
puts Problem15.new.solve