Last active
September 21, 2017 13:26
-
-
Save Pablo-R/8534f299e95116554481754e760c59ca to your computer and use it in GitHub Desktop.
Roman Numerals Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
class RomanNumerals | |
ROMAN_VALUES = { | |
'M' => 1000, | |
'CM' => 900, | |
'D' => 500, | |
'CD' => 400, | |
'C' => 100, | |
'XC' => 90, | |
'L' => 50, | |
'XL' => 40, | |
'X' => 10, | |
'IX' => 9, | |
'V' => 5, | |
'IV' => 4, | |
'I' => 1 | |
} | |
def self.to_arabic_number roman | |
result = 0 | |
return result if roman.empty? | |
roman.each_char.with_index do |char, index| | |
char_number_value = ROMAN_VALUES[char] | |
next_char_number_value = ROMAN_VALUES[roman[index+1]] | |
(!next_char_number_value.nil? && char_number_value < next_char_number_value) ? result-= char_number_value : result += char_number_value | |
end | |
return result | |
end | |
def self.to_roman_numeral number | |
result = '' | |
return result if number == 0 | |
ROMAN_VALUES.values.each do |divisor| | |
if number >= divisor | |
quotient, remainder = number.divmod(divisor) | |
#debugger | |
result += ROMAN_VALUES.key(divisor) * quotient | |
number = remainder | |
end | |
end | |
return result | |
end | |
end | |
class IO | |
def self.read file | |
input_file = File.foreach(file) do |line| | |
string_line_number = line.delete("\n") | |
if string_line_number.match(/\AM{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\z/) | |
puts RomanNumerals.to_arabic_number string_line_number | |
elsif line.to_i.between?(1,3999) | |
puts RomanNumerals.to_roman_numeral string_line_number.to_i | |
end | |
end | |
end | |
end | |
#IO.read "sample.txt" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍