2
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.

マルチスケールシミュレーション特論10

Last updated at Posted at 2020-11-25

!Mac OS X-10.15.7 !ruby-2.7.1p83

Recursive Fibonacci

講義ページリンク

チャート式ruby-V(Recursive Fibonacci)

内容

rubyで再帰処理

課題

フィボナッチ数列を計算するプログラムの作成

解答例

"assert_equal.rb"
#!/usr/bin/env ruby
# frozen_string_literal: true

def fib(n)
  if n.zero?
    0
  elsif n == 1
    1
  else
    fib(n - 1) + fib(n - 2)
  end
end

require './assert_equal'
[[0, 0], [1, 1], [2, 1], [3, 2], [4, 3],
 [5, 5], [6, 8], [7, 13], [8, 21]].each do |index, expected|
  puts assert_equal(expected, fib(index))
end

出力

> ruby fibonacci.rb
expected: 0
result: 0
succeeded in assert_equal.

expected: 1
result: 1
succeeded in assert_equal.

expected: 1
result: 1
succeeded in assert_equal.

expected: 2
result: 2
succeeded in assert_equal.

expected: 3
result: 3
succeeded in assert_equal.

expected: 5
result: 5
succeeded in assert_equal.

expected: 8
result: 8
succeeded in assert_equal.

expected: 13
result: 13
succeeded in assert_equal.

expected: 21
result: 21
succeeded in assert_equal.

NOTE

  • 再帰処理は他のプログラミング言語と同じように書ける
  • rubocopいわくfibというmethod名は短いらしいけど特に問題ないので無視する

  • source ~/multiscalesim_toku/grad_members_20f/members/lynd2299/mss10.org
2
0
0

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
2
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?