Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created February 4, 2025 01:18
Show Gist options
  • Save JoelQ/83bc02f962035159296a417874dcb9a2 to your computer and use it in GitHub Desktop.
Save JoelQ/83bc02f962035159296a417874dcb9a2 to your computer and use it in GitHub Desktop.
Recursive cached fibonnacci
fib = Hash.new do |hash, n|
puts "calculating fib #{n}"
# base case
if n == 0 || n == 1
hash[n] = 1
else
# recursive case
hash[n] = hash[n - 1] + hash[n - 2]
end
end
> fib[3]
# calculating fib 3
# calculating fib 2
# calculating fib 1
# calculating fib 0
# => 3
fib[1]
# => 1
> fib[5]
# calculating fib 5
# calculating fib 4
# => 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment