Last active
January 2, 2016 12:49
-
-
Save bjhaid/8306312 to your computer and use it in GitHub Desktop.
Roman Numerals
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
class RomanNumerals | |
NUM_TO_ROMAN = { 1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X' , 9 => 'IX', 5 => 'V', 4 => 'IV', 1 => 'I' } | |
class << self | |
def to_roman(num) | |
NUM_TO_ROMAN.each_with_object("") { |(k,v), mem| mem << (v * (num / k)); num = num % k } | |
end | |
def from_roman(roman) | |
num = 0 | |
transpose = Hash[NUM_TO_ROMAN.map{ |k, v| [v,k] }] | |
two_val_romans = /#{NUM_TO_ROMAN.values.select { |v| v.size == 2}.join("|")}/ | |
roman = roman.gsub(two_val_romans) { |word| num += transpose[word]; "" } | |
roman.chars.to_a.inject(num) { |n,chr| n += transpose[chr].to_i } | |
end | |
end | |
end | |
RomanNumerals.to_roman(1540) # => "MDXL" | |
RomanNumerals.to_roman(1590) # => "MDXC" | |
RomanNumerals.from_roman("MDXL") # => 1540 | |
RomanNumerals.from_roman("MDXC") # => 1590 | |
RomanNumerals.from_roman("XIX") # => 19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment