做项目 euler #2 的更多红宝石方式 [英] more ruby way of doing project euler #2

查看:38
本文介绍了做项目 euler #2 的更多红宝石方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Ruby,并且正在解决一些 Project Euler 问题.我这样解决了问题二:

I'm trying to learn Ruby, and am going through some of the Project Euler problems. I solved problem number two as such:

def fib(n)
  return n if n < 2
  vals = [0, 1]
  n.times do
    vals.push(vals[-1]+vals[-2])
  end
  return vals.last
end
i = 1
s = 0
while((v = fib(i)) < 4_000_000)
  s+=v if v%2==0
  i+=1
end
puts s

虽然这可行,但它似乎不太像 ruby​​-ish——我无法像第一个那样想出任何好的纯 Ruby 答案( puts (0..999).inject{ |sum, n| n%3==0||n%5==0 ? sum : sum+n }).

While that works, it seems not very ruby-ish—I couldn't come up with any good purely Ruby answer like I could with the first one ( puts (0..999).inject{ |sum, n| n%3==0||n%5==0 ? sum : sum+n }).

推荐答案

要获得好的解决方案,为什么不创建一个斐波那契数生成器,例如 PrimeTriangular示例我在此处提供.

For a nice solution, why don't you create a Fibonacci number generator, like Prime or the Triangular example I gave here.

由此,您可以使用漂亮的 Enumerable 方法来处理问题.您可能想知道偶数斐波那契数是否也有任何模式.

From this, you can use the nice Enumerable methods to handle the problem. You might want to wonder if there is any pattern to the even Fibonacci numbers too.

编辑您的问题以发布您的解决方案...

Edit your question to post your solution...

注意:有比列举它们更有效的方法,但它们需要更多的数学运算,不会像这个一样清楚,只有当 400 万更高时才会发光.

Note: there are more efficient ways than enumerating them, but they require more math, won't be as clear as this and would only shine if the 4 million was much higher.

由于 demas' 已经发布了一个解决方案,这里是一个清理过的版本:

As demas' has posted a solution, here's a cleaned up version:

class Fibo
  class << self
    include Enumerable

    def each
      return to_enum unless block_given?
      a = 0; b = 1
      loop do
        a, b = b, a + b
        yield a
      end
    end
  end
end

puts Fibo.take_while { |i| i < 4000000 }.
          select(&:even?).
          inject(:+)

这篇关于做项目 euler #2 的更多红宝石方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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