斐波那契一线车 [英] Fibonacci One-Liner

查看:43
本文介绍了斐波那契一线车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Ruby单行代码解决 Project Euler 中的问题,我很好奇对于第二个问题:

I'm trying to solve questions from Project Euler in Ruby one-liners, and I'm curious if there's a more elegant solution for question two:

斐波那契数列中的每个新术语都是通过将前两个术语相加而生成的.从1和2开始,前10个术语将是:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1、2、3、5、8、13、21、34、55、89,...

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

通过考虑斐波那契数列中值不超过400万的项,找到偶值项的总和.

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

这是我在Ruby中的一线解决方案:

Here is my one line solution in Ruby:

(1..32).inject([0,1]) {|arr, i| (arr << arr[-1] + arr[-2] if arr[-1] + arr[-2] <= 4000000) || arr}.inject(0) {|total, i| total += i.even? ? i : 0}

我在这里主要担心的是,我使用范围(1..32)只是因为我碰巧知道在斐波那契数列中的数字开始超过4,000,000之前,这是所有必要的.我希望将其以某种方式内置到一行中,但我无法弄清楚.

My main concern here is that I'm using the range (1..32) only because I happen to know that that's all that's necessary until numbers in the Fibonacci sequence begin to exceed 4,000,000. I would prefer that this be built into the one-line somehow, but I haven't been able to figure it out.

不允许使用分号!

推荐答案

灵感来自Alex的答案:

Inspired on Alex's answer:

# Ruby 1.8.7
f = lambda { |x| x < 2 ? x : f.call(x-1) + f.call(x-2) }
puts f.call(6)   #=> 8

# Ruby 1.9.2
f = ->(x){ x < 2 ? x : f[x-1] + f[x-2] }
puts f[6]        #=> 8

这篇关于斐波那契一线车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆