Let's solve the roman numerals

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)

!ruby 2.7.1p83

Recommended Posts

Let's solve the roman numerals
Let's solve the FizzBuzz problem!
roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
Roman Numerals
roman numerals
roman numerals
EX1: roman numerals
Let's understand the function!
Have the JVM solve Sudoku
Let's make the app better
Let's understand the if statement!
Let's try the S2Struts tutorial (# 3_180425)
Let's understand the guard statement!
Let's try the S2Struts tutorial (# 5_180526)
Let's try the S2Struts tutorial (# 4_180505)
Let's try the S2Struts tutorial (# 1_180423)
Let's understand the for-in statement!
Let's try the S2Struts tutorial (# 2_180424)
Find Roman numerals in Ruby
Let's understand the switch statement!
Let's try the S2Struts tutorial (# 0_yymmdd)
Let's understand the Array (Element) type!
Yes, let's preview the image. ~ part5 ~
Image processing: Let's play with the image
Let's understand the Optional (Wrapped) type!
Let's attack the vulnerability (2) Open redirect
[Beginner] Let's solve AtCoder problem with Ruby while looking at the article!