https://qiita.com/knkrhs/items/27440e1c7f75cc5f53f0
Challenges Write a method that takes arabic numerals and returns roman numerals
Cheeks, it's pretty interesting. So, let's solve this. It's New Year's Eve, and sometimes it's good!
digittoarabic.rb
DigitToRoman = Struct.new(:arabic, :roman )
def roman(n)
#Supports from 1 to 3999
if n <= 0 || n >= 4000 then
raise "Invalid input(" + n.to_s + ")"
end
#Create a table for conversion.
#Actually, it is better to use initilize timing in Class.
v = Array.new()
v.push ( DigitToRoman.new( 1000, "M") )
v.push ( DigitToRoman.new( 900, "CM") )
v.push ( DigitToRoman.new( 500, "D") )
v.push ( DigitToRoman.new( 400, "CD") )
v.push ( DigitToRoman.new( 100, "C") )
v.push ( DigitToRoman.new( 90, "XC") )
v.push ( DigitToRoman.new( 50, "L") )
v.push ( DigitToRoman.new( 40, "XL") )
v.push ( DigitToRoman.new( 10, "X") )
v.push ( DigitToRoman.new( 9, "IX") )
v.push ( DigitToRoman.new( 5, "V") )
v.push ( DigitToRoman.new( 4, "IV") )
v.push ( DigitToRoman.new( 1, "I") )
#Reverse sort
#You can sort and then reverse, but the cost is ...
#If you don't sort, the result will change if the push order above changes.
v = v.sort{|a,b| -( a.arabic <=> b.arabic ) }
#Conversion to Roman numeral strings.
#Eliminate loops in the conversion table by using inject
#Also, a character string*Make a string with numbers and repeat
v.inject("") { |ret, m|
i = n / m.arabic
n = n % m.arabic
ret + m.roman * i
}
end
num = ARGV[0].to_i
puts ARGV[0] + " = " + roman(num)
Recommended Posts