1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
#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.
describe "problem two" do
def fib
Enumerator.new do |yielder|
x, y = 1, 2
loop do
yielder.yield x
tmp = x
x = y
y = tmp + y
end
end
end
def sum_of_first(n)
fib.take(n).inject(0) do |memo, x|
memo + x
end
end
it "computes the sum" do
result = sum_of_first(10)
expect(result).to eql([1, 2, 3, 5, 8, 13, 21, 34, 55, 89].inject(0) {|memo, x| memo + x })
end
it "accumulates" do
items = fib.take_while { |n| n < 4_000_000 }.find_all(&:even?)
result = items.inject(0) { |memo, x| memo + x }
expect(result).to eql(4613732)
end
it "can accumulates manually" do
total = 0
enumerator = fib
current = enumerator.next
loop do
break if current >= 4_000_000
total += current if current.even?
current = enumerator.next
end
expect(total).to eql(4613732)
end
end
|