After seeing the article "I tried to solve the tribonacci sequence problem with Ruby (time limit 10 minutes)", I thought I wanted to write it recursively. So Kakiko ... is a lie, and I didn't really know what Tribonacci was, so I wrote it in a hurry.

```
# Tribonacci
def tribonacci n
if n == 1
return 1
elsif n == 2
return 1
elsif n == 3
return 2
else
return tribonacci(n - 3) + tribonacci(n - 2) + tribonacci(n - 1)
end
end
p (1..10).map{|n| tribonacci n } # => [1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
# Unit Test
require 'test/unit'
class TC_Foo < Test::Unit::TestCase
def test_one
assert_equal tribonacci(1), 1
end
def test_two
assert_equal tribonacci(2), 1
end
def test_three
assert_equal tribonacci(3), 2
end
def test_ten
assert_equal tribonacci(10), 149
end
end
```

What about tail call optimization? Or memoization? Or, write in a loop instead of recursion in the first place! Write in Haskell or Elm because it's a great opportunity! , If you write with an iterator? Ignore such an inner voice. Because I'm not confident of doing them in 10 minutes!

Fibonacci, Tribonacci, Tetranatch with Ruby's repeat function!

Recommended Posts