Created
December 4, 2012 07:56
-
-
Save simonkro/4201665 to your computer and use it in GitHub Desktop.
Another Version
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
def digit_to_roman digit, one, five, ten | |
case d = digit % 10 | |
when 0..3 then one * d | |
when 4 then one + five | |
when 5..8 then five + one * (d - 5) | |
when 9 then one + ten | |
end | |
end | |
def to_roman n | |
digit_to_roman(n / 1000, 'M', '', '') + | |
digit_to_roman(n / 100, 'C', 'D', 'M') + | |
digit_to_roman(n / 10, 'X', 'L', 'C') + | |
digit_to_roman(n, 'I', 'V', 'X') | |
end | |
def from_roman n | |
@roman_to_arabic ||= Hash[(1..3999).map{|i| [to_roman(i), i]}] | |
@roman_to_arabic[n.chomp] | |
end | |
def convert n | |
n =~ /\d/ ? to_roman(n.to_i) : from_roman(n) | |
end | |
ARGF.each_line {|l| puts convert(l)} if $0 == __FILE__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment