rubyfibonacci

Fibonacci One-Liner


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:

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, ...

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

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}

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.

Semi-colons are not allowed!


Solution

  • 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