Created
June 1, 2017 21:30
-
-
Save rantler/1d76ca2193c9a3e5f7c14675f5295d63 to your computer and use it in GitHub Desktop.
Example of fast fibonacci algorithm in Ruby
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
# Cribbed from https://stackoverflow.com/questions/24438655/ruby-fibonacci-algorithm | |
def fib_memo(n, memo) | |
memo[n] ||= fib_memo(n-1, memo) + fib_memo(n-2, memo) | |
end | |
def fib(n) | |
raise "fib not defined for negative numbers" if n < 0 | |
fib_memo(n, [0, 1]) | |
end | |
def timer | |
n = Time.now | |
yield | |
puts "#{(Time.now - n) * 1_000}ms" | |
end | |
timer { fib(42) } # 0.013ms on my laptop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment