1

I am trying to solve a Fibonacci solution in HackerRanck.

  • I am mostly using the inject method.
  • I first declared an empty array.
  • I then define a method that takes in a parameter and turns it into a list that stores two initial values, 0 and 1.
  • The method then takes the last two values and sum them up together and returns the newly-formed list. (I hope I got this logic right)

I was then aiming at calling the method and loop through it this time around summing all the even values in it and returning the final result.

#!/bin/ruby

t = gets.strip.to_i
for a0 in (0..t-1)
    n = gets.strip.to_i
end

result = 0

def fibbonacci num
    (1..num).inject([0, 1]) { |fib| << fib.last(2).inject(:+)}
end

my_fib_num = fibbonacci n

for i in my_fib_num
    if i % 2 == 0
        result.inject(0){|sum,x| sum + x }
    end
end```

Anything I could be getting wrong here?
  • See my comment on [this SO question](https://stackoverflow.com/questions/61872291/how-does-ruby-enumerator-terminate-iteration). – Cary Swoveland Jul 25 '20 at 07:51

2 Answers2

1

I see you are doing unnecessary things over here and you are using inject in completely wrong way. The inject should always be called on an array or a range object. On every loop the result of the loop will be assigned to first parameter (i.e result in the example below) of the block and it will be passed back again to next loop. Finally returns the value in result.

The updated code:

#!/bin/ruby

t = gets.strip.to_i
def fibbonacci(num)
    (1..num).inject([0, 1]) { |result| result << result.last(2).inject(:+)}
end
my_fib_num = fibbonacci(t)
result = my_fib_num.inject(:+)

Note: The solution is to solve by using inject.

Ref: https://apidock.com/ruby/Enumerable/inject

Deepak
  • 138
  • 1
  • 10
0

May be you can use select and inject together to some the even

t = gets.strip.to_i

def fibbonacci(num)
  (1..num).inject([0, 1]) { |fib| fib << fib.last(2).inject(:+)}
end

my_fib_num = fibbonacci(t)
my_fib_num.keep_if{|d| d.even?}.inject(:+)