Created
February 4, 2025 01:18
-
-
Save JoelQ/83bc02f962035159296a417874dcb9a2 to your computer and use it in GitHub Desktop.
Recursive cached fibonnacci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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