Skip to content

Instantly share code, notes, and snippets.

@chipit24
Created April 8, 2015 02:08
Show Gist options
  • Save chipit24/31adb3085616b0da69f3 to your computer and use it in GitHub Desktop.
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.
# 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