Created
September 27, 2018 12:07
-
-
Save Dreniak/3aa972df492507debdabeadad7934df7 to your computer and use it in GitHub Desktop.
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
def fibs(n) | |
fib = [0, 1] | |
while fib.length < n | |
fib << fib[-1] + fib[-2] | |
end | |
fib.slice(0, n) | |
end | |
def fibs_rec(n) | |
return [0,1].slice(0, n) if n <= 2 | |
a = fibs_rec(n-1) | |
a << a[-1] + a[-2] | |
end | |
def fibs_single(n) | |
return n <= 2 ? [0, 1].slice(0,n) : fibs_single(n-1) << fibs_single(n-1)[-1] + fibs_single(n-1)[-2] | |
end | |
def time_measure | |
fibs_start = Time.now.to_f | |
fibs(10) | |
fibs_end = Time.now.to_f | |
puts fibs_end - fibs_start | |
fibs_rec_start = Time.now.to_f | |
fibs_rec(10) | |
fibs_rec_end = Time.now.to_f | |
puts fibs_rec_end - fibs_rec_start | |
fibs_single_start = Time.now.to_f | |
fibs_single(10) | |
fibs_single_end = Time.now.to_f | |
puts fibs_single_end - fibs_single_start | |
end | |
p fibs(8) # => | |
p fibs_rec(8) # => | |
p fibs_single(8) # => | |
time_measure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment