Created
April 17, 2014 21:56
-
-
Save varyform/11013785 to your computer and use it in GitHub Desktop.
fib with memo
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
# Fibonacci numbers WITH memoization. | |
# Initialize the memoization array. | |
@scratchpad = [] | |
# Calculate the nth Fibonacci number, f(n). | |
def fibo(n) | |
if n <= 1 | |
n | |
else | |
@scratchpad[n] ||= fibo(n-1) + fibo(n-2) | |
end | |
end | |
# Display the Fibonacci sequence. | |
1.upto 100 do |number| | |
puts "fibo(#{number}) = #{fibo(number)}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment