roman numerals

Introduction

This time, in the following article, implement the function to \ _roman that receives Arabic numerals and returns Roman numerals with ruby.

roman numerals

If there are many boundary values ​​and the array is full of ifs, an implementation technique of putting boundary values ​​in an array and turning it in a loop may be used. This time, this method is effective, so I will use it.

roman_numerals.rb


def to_roman(n)
  raise RangeError if n <= 0 or 4000 <= n

  arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
  roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
  ret = ""
  arabic_num.zip(roman_num) do |arabic, roman|
    while n >= arabic do
      n -= arabic
      ret << roman
    end
  end
  return ret
end

Development issues

Let's add this function as a method of Integer class.

roman_numerals.rb


class Integer
  def to_roman
    n = self
    raise RangeError if n <= 0 or 4000 <= n

    arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
    roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
    ret = ""
    arabic_num.zip(roman_num) do |arabic, roman|
      while n >= arabic do
	n -= arabic
	ret << roman
      end
    end
    return ret
  end
end

Then you can use it as follows.

roman_numerals.rb


3999.to_roman # => "MMMCMXCIX"

Recommended Posts

roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
Roman Numerals
roman numerals
roman numerals
EX1: roman numerals
Let's solve the roman numerals
Find Roman numerals in Ruby
Convert numbers to Roman numerals in Ruby
roman numerals (I tried to simplify it with hash)