# [Ruby] I tried solving the problem of Tribonacci sequence in Ruby, with recursion.

After seeing the article, “I tried to solve the problem of Tribonacci sequence in Ruby (time limit 10 minutes)” (https://qiita.com/keisuke_oyatu/items/43c0100f885c2050b956) and thought that I wanted to write it recursively. So Kakiko was a lie, and I didn’t really know what Tribonacci was, so I wrote it impatiently.

# Code

``````# 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
``````

# in conclusion

Tail call optimization? Or is it memoization? Or write it in a loop, not in the first place! , It’s a great opportunity to write in Haskell or Elm! , Write iterator? Ignore such inner voice. Because I don’t have the confidence to do them in 10 minutes!

# [PR] ** Praise HP12c**

Ruby repeat function Fibonacci, Tribonacci, Tetra Natch!

Tags:

Updated: