Hi,
Roelof W. wrote in post #1077938:
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
The problem is that you (unintentionally) start the sum with 1 instead
of 0. When you don’t set a start value for inject, the aggregate value
is set to the first element. In this case it’s 1, so the result will be
1 too big.
Also your code is rather “naive” in the sense that you’re treating the
numbers as if they were physical objects and actually needed to be
collected. This is very inefficient and completely unnessary. You only
need to track the last two numbers.
You should also get rid of some habits you seem to have adopted from
other programming languages (like Java or so). Things like “Array.new
[1,2]” and “number % 2 == 0” are useless in Ruby. The literal “[1,2]”
already is an array. And checking if an integer is even can be done by
simply calling “even?”.
A low-level solution might look something like this:
previous, current =
0, 1
sum = 0
while current <= 4_000_000
sum += current if current.even?
previous, current =
current, previous + current
end
puts sum
A more high-level approach could consist of defining an Enumerator for
the fibonacci sequence and then apply “take_while”, “select” and
“reduce” subsequently:
fibonacci = Enumerator.new do |yielder|
previous, current =
0, 1
yielder << previous
loop do
yielder << current
previous, current =
current, previous + current
end
end
sum = fibonacci.take_while{|e| e <= 4_000_000}.select(&:even?).reduce :+
puts sum
This actually works similar to your code, so it’s not efficient. But
it’s very readable and kind of “the Ruby way”.