6
1

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.

アラビア数字をローマ数字に変換する

Last updated at Posted at 2020-11-18

概要

アラビア数字を受け取り、ローマ数字を返す method を Ruby で作成する

ローマ数字: https://ja.wikipedia.org/wiki/%E3%83%AD%E3%83%BC%E3%83%9E%E6%95%B0%E5%AD%97

コード

 1  $table = {1=> 'I', 4=> 'IV', 5=> 'V', 9=> 'IX', 10=> 'X', 40=> 'XL', 50=> 'L', 90=> 'XC', 100=> 'C', 400=> 'CD', 500=> 'D', 900=> 'CM', 1000=> 'M'}
 2  
 3  # reverse sort
 4  $table = Hash[ $table.sort.reverse ]
 5  
 6  
 7  def arabic2roman(arabic_num)
 8    if arabic_num.between?(1,3999)
 9      # initialize
10      i = arabic_num
11      roman_num = ''
12  
13      for s in $table.keys
14        if i == 0
15  	break
16        else
17  	# q: quotient, r: remainder
18  	q = i / s
19  	r = i % s
20  	# update
21  	i = r
22  	roman_num += $table[s] * q
23        end
24      end
25      return roman_num
26    end
27  end

以下の行を追加して、コードをテストする

test = [1, 2, 4, 5, 6, 9, 10, 11, 14, 15, 19, 38, 42, 49, 51, 97, 99, 439, 483, 499, 732, 961, 999, 1999]

test.each do |num|
  puts "#{num} #{arabic2roman(num)}"
end

結果は以下の通り

1 I
2 II
4 IV
5 V
6 VI
9 IX
10 X
11 XI
14 XIV
15 XV
19 XIX
38 XXXVIII
42 XLII
49 XLIX
51 LI
97 XCVII
99 XCIX
439 CDXXXIX
483 CDLXXXIII
499 CDXCIX
732 DCCXXXII
961 CMLXI
999 CMXCIX
1999 MCMXCIX

Ruby初心者なので、キレイなコードではないかもしれません

これからもっとRubyについて学んでいきたいと思います!


  • source ~/doc/lecture/multi-scale/grad_members_20f/members/yukiue/docs/roman_numerals.org
6
1
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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?