Math Pro 數學補給站's Archiver

去喜歡身旁的每一個事物,
去愛身旁的每一個人,
不要等到失去了才知道如何去珍惜和擁有。

weiye 發表於 2006-3-5 23:13

[Ruby] Fibonacci 數列....

[b][i]新聞群組: [url=http://groups.google.com/group/comp.lang.ruby]comp.lang.ruby[/url]
"Peter Ertl" <p...@gmx.org>
日期: Thu, 15 Dec 2005 03:16:29 +0900
主旨: ruby beats them all[/i][/b]


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

[code]def fibonacci(n)
  a, b = 1, 1
  n.times do
    a, b = b, a + b
  end
  a
end [/code]

elegance beats ignorance (ruby vs. java)

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

[b][i]Christian Neukirchen <chneukirc...@gmail.com>
日期:Thu, 15 Dec 2005 04:27:08 +0900[/i][/b]

That's not functional...

How about really doing it functional?

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

:)

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

[b][i]Edward Faulkner <e...@alum.mit.edu>
日期: Thu, 15 Dec 2005 04:58:15 +0900[/i][/b]

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

[code]def fib(n)
    n > 1 ? fib(n-1) + fib(n-2) : n
end [/code]

You can even make it run efficiently by memoizing it.  :-)


-Ed

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

[b][i]"Andrew Backer" <awbac...@gmail.com>
日期: 14 Dec 2005 22:37:43 -0800[/i][/b]

[code]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 [/code]

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 :)

頁: [1]

論壇程式使用 Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.