發新話題
打印

[Ruby] Fibonacci 數列....

推到噗浪
推到臉書

[Ruby] Fibonacci 數列....

新聞群組: comp.lang.ruby
"Peter Ertl" <p...@gmx.org>
日期: Thu, 15 Dec 2005 03:16:29 +0900
主旨: ruby beats them all



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>
日期:Thu, 15 Dec 2005 04:27:08 +0900


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>
日期: Thu, 15 Dec 2005 04:58:15 +0900


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>
日期: 14 Dec 2005 22:37:43 -0800
複製內容到剪貼板
代碼:
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

發新話題