Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.