Last active
December 20, 2015 15:19
-
-
Save shunwen/6153719 to your computer and use it in GitHub Desktop.
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
module RomanNumeral | |
VALUES_OF_LETTERS = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 } | |
MODERN_ROMAN_PATTERNS = { CM: 900, CD: 400, XC:90, XL: 40, IX: 9, IV: 4 } | |
def self.i_to_old_roman int | |
i_to_roman int, VALUES_OF_LETTERS | |
end | |
def self.i_to_modern_roman int | |
i_to_roman int, VALUES_OF_LETTERS.merge(MODERN_ROMAN_PATTERNS) | |
end | |
def self.i_to_roman int, pattern | |
roman = "" | |
pattern.sort_by {|k,v| v}.reverse.each do |pair| | |
roman += pair[0].to_s * (int / pair[1]) | |
int = int % pair[1] | |
end | |
roman | |
end | |
end | |
RomanNumeral.i_to_modern_roman 179 # => "CLXXIX" | |
RomanNumeral.i_to_modern_roman 2019 # => "MMXIX" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment