Skip to content

Instantly share code, notes, and snippets.

View chipit24's full-sized avatar

Robert Komaromi chipit24

View GitHub Profile
@chipit24
chipit24 / fibonacci.rb
Created April 8, 2015 02:08
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