Last active
December 30, 2015 06:39
-
-
Save dliberalesso/7790813 to your computer and use it in GitHub Desktop.
Roman to-from Numeral in Ruby
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
class RomanNumerals | |
MAX = 4999 | |
FACTORS = [['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_roman(i) | |
if i <= 0 || i > MAX then fail "Roman values must be > 0 and <= #{MAX}" end | |
roman = '' | |
for code, factor in FACTORS | |
count, i = i.divmod(factor) | |
roman << (code * count) | |
end | |
roman | |
end | |
def self.from_roman(r) | |
numeral = 0 | |
for code, factor in FACTORS | |
while r.index(code) == 0 | |
numeral += factor | |
r.slice!(code) | |
end | |
end | |
numeral | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment