Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active December 16, 2015 22:39
Show Gist options
  • Save jgaskins/5508580 to your computer and use it in GitHub Desktop.
Save jgaskins/5508580 to your computer and use it in GitHub Desktop.
Demonstrating recursive Fibonacci calculation visits each node in the sequence the number of times corresponding to its position in the calculation. So fib[n] == fib.calls[max_calculated - n].
class Fibonacci
attr_reader :fibs, :calls
def initialize
@fibs = [0, 1]
@calls = Hash.new { |h, k| h[k] = 0 }
end
def [] position
calls[position] += 1
return fibs[position] if fibs[position]
self[position - 1] + self[position - 2]
end
end
fib = Fibonacci.new
p fib[30].calls
# {
# 30=>1,
# 29=>1,
# 28=>2,
# 27=>3,
# 26=>5,
# 25=>8,
# 24=>13,
# 23=>21,
# 22=>34,
# 21=>55,
# 20=>89,
# 19=>144,
# 18=>233,
# 17=>377,
# 16=>610,
# 15=>987,
# 14=>1597,
# 13=>2584,
# 12=>4181,
# 11=>6765,
# 10=>10946,
# 9 =>17711,
# 8 =>28657,
# 7 =>46368,
# 6 =>75025,
# 5 =>121393,
# 4 =>196418,
# 3 =>317811,
# 2 =>514229,
# 1 =>832040,
# 0 =>514229
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment