[Ruby] Fibonacci 數列....

[Ruby] Fibonacci 數列....

"Peter Ertl" <p...@gmx.org>

that why I love ruby (and functional languages in general)

代碼:
def fibonacci(n)
a, b = 1, 1
n.times do
a, b = b, a + b
end
a
end
elegance beats ignorance (ruby vs. java)

---------------------------------------------------------------------------------

Christian Neukirchen <chneukirc...@gmail.com>

That's not functional...

How about really doing it functional?

代碼:
def fib(n)
(1..n-2).inject([1, 1]) { |(a, b), n| [b, a+b] }.last
end
:)

---------------------------------------------------------------------------------

Edward Faulkner <e...@alum.mit.edu>

If we're talking about elegance, I prefer this one.  It reads just
like the definition of the sequence:

代碼:
def fib(n)
n > 1 ? fib(n-1) + fib(n-2) : n
end
You can even make it run efficiently by memoizing it.  :-)

-Ed

---------------------------------------------------------------------------------

"Andrew Backer" <awbac...@gmail.com>

代碼:
def calc_iterative(n)
a = [0,1,0]
for i in 2..n
a[k] = a[k-1] + a[k-2]
end
return a[n%3]
end
I like this one, since it uses array wrapping.  So many ways to write
it that are all *slightly*  different... But this was to show someone,
so :)

TOP

﻿