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

roman numerals

Posted at

ruby-2.7.1p83

問題文

アラビア数字 (arabic numerals) を受け取って, ローマ数字 (roman numerals) を返す method を書け.
https://qiita.com/daddygongon/items/2d0a73a51ddab2d9da1b

解法(途中までしかできていない)

まず単純に1~5までを出力させてみる。

def to_roman(arabic)
  if arabic == 1
    p "I"
  elsif arabic == 2
    p "II"
  elsif arabic == 3
    p "III"
  elsif arabic == 4
    p "IV"
  elsif arabic == 5
    p "V"
  else
    p "false"
  end
end

if $PROGRAM_NAME == __FILE__
  arabic = ARGV[0].to_i
  to_roman(arabic)
end

これは成功する。

次に、ループを使った形に変形する。

def to_roman(arabic_numerals)
  arabic_and_roman = [[1,"I"], [2,"II"], [3,"III"], [4,"IV"], [5,"V"]]

  arabic_and_roman.each do |arabic, roman|
    if arabic_numerals == arabic
      return roman      
    end
  end
  puts(false)
end

これも成功した。1~5以外の数字や何も入力がない場合はfalseとなる。

手作業が多いが、arabic_and_roman変数に、表記が変わるポイントの数字を並べることにした。

この時点では表記されていない数字はfalseになってしまうので、ifで条件分岐していこうとしたが最後までは解けなかった。

def to_roman(arabic_numerals)
  arabic_and_roman = [[1,"I"], [4,"IV"], [5,"V"], [9,"IV"], [10,"X"], [40,"XL"], [50,"L"], [90,"XC"], [100,"C"], [400,"CD"], [500,"D"], [900,"CM"], [1000,"M"]]

  arabic_and_roman.each do |arabic, roman|
    if arabic_numerals == arabic
      return roman      
    end
  end
  puts(false)
end

if $PROGRAM_NAME == __FILE__
  arabic_numerals = ARGV[0].to_i
  puts(to_roman(arabic_numerals))
end

  • source ~/grad_members_20f/members/o-michika/roman_numerals.org
1
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
1
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?