'Fibonacci sequence in Ruby
def fibonacci(n)
n <= 1 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 )
end
puts fibonacci( 6)
Can somebody explain how this code works. I realise that it works due to recursion but i cannot figure it out gradually. Will be gratefull for step by step explanation.
Solution 1:[1]
Does this help you visualise it?:
def fibonacci(n, level = 0)
puts ('| ' * level) + 'n: ' + n.to_s
res = n <= 1 ? n : fibonacci(n - 1, level + 1) + fibonacci(n - 2, level + 1)
puts ('| ' * level) + 'res: ' + res.to_s
res
end
irb(main):038:0> fibonacci(6)
n: 6
| n: 5
| | n: 4
| | | n: 3
| | | | n: 2
| | | | | n: 1
| | | | | res: 1
| | | | | n: 0
| | | | | res: 0
| | | | res: 1
| | | | n: 1
| | | | res: 1
| | | res: 2
| | | n: 2
| | | | n: 1
| | | | res: 1
| | | | n: 0
| | | | res: 0
| | | res: 1
| | res: 3
| | n: 3
| | | n: 2
| | | | n: 1
| | | | res: 1
| | | | n: 0
| | | | res: 0
| | | res: 1
| | | n: 1
| | | res: 1
| | res: 2
| res: 5
| n: 4
| | n: 3
| | | n: 2
| | | | n: 1
| | | | res: 1
| | | | n: 0
| | | | res: 0
| | | res: 1
| | | n: 1
| | | res: 1
| | res: 2
| | n: 2
| | | n: 1
| | | res: 1
| | | n: 0
| | | res: 0
| | res: 1
| res: 3
res: 8
=> 8
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben Stephens |
