Last active
June 27, 2020 14:31
-
-
Save mohkale/c02f872d3cfd04d944deaf381aa62911 to your computer and use it in GitHub Desktop.
memoized fibonacci
This file contains hidden or 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
class Fib | |
def fib(i) | |
memory.fetch(i) do | |
val = if i <= 1 | |
[i,0].max | |
else | |
fib(i-1) + fib(i-2) | |
end | |
memory[i] = val | |
end | |
end | |
private | |
def memory | |
@memory ||= {} | |
end | |
end | |
puts Fib.new.fib(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment