Last active
September 9, 2018 21:32
-
-
Save MarioRuiz/42ce1e5ecadd85e6c77bd2a763418022 to your computer and use it in GitHub Desktop.
Four different Ruby examples creating the Fibonacci sequence and calculating time consuming.
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
require 'timify' | |
num=36 | |
t=Timify.new :count, show:false | |
## Example 1 | |
t.add | |
f = lambda { |x| x < 2 ? x : f.call(x-1) + f.call(x-2) } | |
puts f.call(num) | |
t.add :example1 | |
## Example 2 | |
f = ->(x){ x < 2 ? x : f[x-1] + f[x-2] } | |
puts f[num] | |
t.add :example2 | |
## Example 3 | |
def fibonacci( n ) | |
return n if ( 0..1 ).include? n | |
( fibonacci( n - 1 ) + fibonacci( n - 2 ) ) | |
end | |
puts fibonacci(num) | |
t.add :example3 | |
## Example 4 | |
def fib(n) | |
n < 2 ? n : fib(n-1) + fib(n-2) | |
end | |
puts fib(num) | |
t.add :example4 | |
## Print time consumed by different examples | |
pp t.totals[:labels] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment