Created
April 5, 2018 03:16
-
-
Save StevenJL/1c52a284fd49c4a3cecd0bacbf2646ec to your computer and use it in GitHub Desktop.
Roman Numeral
This file contains hidden or 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
NUMERAL_MAP = { | |
'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 | |
} | |
DEC_TO_NUMERAL_MAP = NUMERAL_MAP.invert | |
def tokenize_roman_numerals(roman_numeral) | |
output = [] | |
len = roman_numeral.length | |
index = 0 | |
while(index < len) | |
mrn, indx_delta = max_roman_numeral(roman_numeral[index...(index+2)]) | |
output << mrn | |
index = index + indx_delta | |
end | |
output | |
end | |
def max_roman_numeral(expression) | |
NUMERAL_MAP.keys.each do |roman_letter| | |
if roman_letter == expression | |
return [roman_letter, 2] | |
end | |
end | |
NUMERAL_MAP.keys.each do |roman_letter| | |
if roman_letter == expression[0] | |
return [roman_letter, 1] | |
end | |
end | |
end | |
# puts tokenize_roman_numerals("MCMXCIX") | |
# ["M", "CM", "XC", "IX"] | |
def from_roman(roman_numeral) | |
output = 0 | |
tokenize_roman_numerals(roman_numeral).each do |rn_token| | |
output = output + NUMERAL_MAP[rn_token] | |
end | |
output | |
end | |
def to_roman(num) | |
output = "" | |
DEC_TO_NUMERAL_MAP.keys.each do |dec| | |
break if num == 0 | |
if num >= dec | |
output = output + DEC_TO_NUMERAL_MAP[dec] | |
num = num - dec | |
end | |
end | |
output | |
end | |
# puts to_roman(1999) | |
# MCMXCIX | |
puts from_roman('MCMXCIX') | |
puts from_roman('XXXVII') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment