EX1: roman numerals

Lecture site

roman numerals

Theme: Number conversion

Create a method that takes Arabic numerals and returns Roman numerals. Arabic numerals are 1 and 2, Roman numerals are I and II, etc.

As a characteristic of Roman numerals, ・ Express numbers by superimposing specific alphabets such as 1: I, 2: II, 3: III. -Characters switch between when the digit is carried up (10: X) and in the middle (5: V). ・ Written in descending order (6: VI, 13: XIII). ・ However, just before the turning point of ↑↑, write a small number to the left of the large number (4: IV, 9: IX).

See wikipedia for details, as it is difficult to understand in theory.

Implementation example

The characters used are VII types of I, V, X, L, C, D, M In particular, the musicians are numbers such as IV and IX that cannot be represented by simply overlapping the alphabets, so these numbers are also treated specially.


class Integer
  def to_roman
    romannum = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M']
    romanval = [ 1,  4,   5,   9, 10,  40,  50, 90, 100, 400, 500, 900, 1000]
    romannum = romannum.reverse
    romanval = romanval.reverse
    result = ''
    len = romannum.length

    i = self

    for j in 0...13
      case
      when i == 0;
	break
      else;
	for k in 0...13
	  case
	  when i - romanval[k] >= 0
	    result += romannum[k]
	    i = i - romanval[k]
	    break
	  end
	end
      end
    end

    result
  end
end

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


if $PROGRAM_NAME == __FILE__
  input.each do |i|
    puts "#{i} #{i.to_roman}"
  end
end

The process of subtracting the number of draws from the largest was repeated,

The execution result looks like this. As far as I confirmed, the numbers are correct

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

note

・ Honestly, I think the program is bad. I am worried about the amount of calculation because I am using a double for loop (Roman numerals can only represent numbers less than 4000, so this is not a problem). I have stopped because it takes too much time, but I want to try to create an accurate program. ・ It seems that it will be easier to find if you make full use of multiplication and division.


Recommended Posts

EX1: roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
Let's solve the roman numerals
Find Roman numerals in Ruby
Convert numbers to Roman numerals in Ruby