Skip to content

Instantly share code, notes, and snippets.

@MarioRuiz
Last active September 9, 2018 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarioRuiz/42ce1e5ecadd85e6c77bd2a763418022 to your computer and use it in GitHub Desktop.
Save MarioRuiz/42ce1e5ecadd85e6c77bd2a763418022 to your computer and use it in GitHub Desktop.
Four different Ruby examples creating the Fibonacci sequence and calculating time consuming.
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