Skip to content

Instantly share code, notes, and snippets.

@Dreniak
Created September 27, 2018 12:07
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 Dreniak/3aa972df492507debdabeadad7934df7 to your computer and use it in GitHub Desktop.
Save Dreniak/3aa972df492507debdabeadad7934df7 to your computer and use it in GitHub Desktop.
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