yurko
12/7/2015 - 7:08 AM

fibonacci

fibonacci

fibo = ->(n) { Enumerator.new { |y, a=[0,1]| loop { y << a[-1]; a << a[-2..-1].reduce(:+) } }.take n } 

# improve it to return n values instead of [0,1] + n
fibo2 = ->(n) { [*1..n].reduce [0,1] { |fib| fib << fib[-2..-1].reduce(:+) } }

fibo[10]

def fibonacci
  # Enumerator.new { |y, a=1, b=1| loop { y << a; a, b = b, a + b } }
  Enumerator.new { |y, a=[0,1]| loop { y << a[-1]; a << a[-2..-1].reduce(:+) } }
end

fibonacci.lazy.select(&:even?).first 10

# using Hash
fib = Hash.new {|h, k| h[k] = k < 3 ? 1 : h[k-1] + h[k-2]}