Created
April 8, 2015 02:08
-
-
Save chipit24/31adb3085616b0da69f3 to your computer and use it in GitHub Desktop.
A Ruby function to calculate the nth Fibonacci number using recursion with memoization.
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
# Initialize the memoization array | |
@cache = [] | |
# Calculate the nth Fibonacci number | |
# using recursion with memoization | |
def fibonacci(n) | |
return n if (0..1).include? n | |
(@cache[n-1] ? @cache[n-1] : @cache[n-1] = fibonacci(n - 1)) + | |
(@cache[n-2] ? @cache[n-2] : @cache[n-2] = fibonacci(n - 2)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment