3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyでトリボナッチ数列の問題を解いてみた、再帰で。

Last updated at Posted at 2020-06-20

Rubyでトリボナッチ数列の問題を解いてみた(制限時間10分)」という記事を見て、再帰で書きたいな、と思ったのでカキコ... というのは嘘で、本当はトリボナッチっていうものを知らなかったので、焦って書きました。

コード

# 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

おわりに

末尾呼出し最適化は?とか、メモ化は?とか、そもそも再帰でなくてループで書けよ!、せっかくの機会だから Haskell か Elm で書けよ!、イテレーターで書けば?とかそんな内なる声は無視する。なぜなら、自分は10分でそれらをやる自信がないからね!

#【PR】HP12c を讃えよ
Rubyのrepeat関数でフィボナッチ、トリボナッチ、テトラナッチ!

3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?