Sequencia Fibonacci

Asked

Viewed 261 times

0

I’m doing a selection process, and they’re asking me to create a Fibonacci sequence, only I don’t know how to create, I even tried (code below) but I didn’t get any results. I have to return element F(0) of the Fibonacci sequence. someone could assist me ?

Code:

class Fibonacci
 def element (n)
  expect (Fibonacci.new.element(0)).to eq 0
  return n if (1..0).include? n
  (element(n - 1) + element (n - 0))
 end
puts element (0)
end
  • See if this helps: link

  • I tried to create this way: def element (f) f = Hash.new {|h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2]} puts f=(0) end but returns me this error: 1) Fibonacci returns the element F(0) of the Fibonacci sequence Failure/Error: expect(Fibonacci.new.element(0)). to eq 0 expected: 0 got: nil (Compared using ==) # . /spec/fibonacci_spec.Rb:5:in `block (2 levels) in <top (required)>'

4 answers

0

I like to reason this way, I hope it helps: 1 - we have 3 positions : predecessor, current and next;

2 - the anticipationr will always receive the current;

3 - the current will always receive the next;

4 - the next had always received current + predecessor.

soon:

predecessor = current

current = next

proximo = current + predecessor

I’m a beginner, but I hope I helped. Good luck!

0

Try this way.

Write the Fibonacci sequence in Ruby:

x, y = 0, 1
10.times do
  puts y
  x, y = y, x + y
end

Java:

class Fib {
  public static void main (String args[]) {
     int x = 0;
     int y = 1;
     int total = 1;
     for (int i=0; i<10; i++) {
       System.out.println(total);
       total = x+y;
       x = y;
       y = total;
     }
   }
}

Result in both cases: 1 1 2 3 5 8 13 21 34 55

  • 1

    I understood how it works !! Now how to return the element of F(0)?

0

Try it this way Lucas:

   def fibonacci( n )
      return  n  if ( 0..1 ).include? n
      ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )
    end
    puts fibonacci( 10 )
  • I tried this way and it won’t either. It returns this error: $ rspec An error occurred while loading . /spec/fibonacci_spec.rb. Failure/Error: puts Fibonacci( 10 ) Nameserve: Undefined method fibonacci' for Fibonacci:Class&#xA;# ./lib/fibonacci.rb:6:in <class:Fibonacci>' # . /lib/Fibonacci.Rb:1:in <top (required)>'&#xA;# ./spec/fibonacci_spec.rb:3:in <top (required)>'

  • I did the test in repl.it and it worked.. (https://repl.it/repls/AggressiveSevereRegression)

  • You really did ! I did it this way by creating a hash "f = Hash.new {|h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2]} puts f=(0) " me null

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.