Created
December 2, 2012 15:42
-
-
Save arnvald/4189376 to your computer and use it in GitHub Desktop.
Roman <> Arabic converter
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
roman = %w(M CM D CD C XC L XL X IX V IV I) | |
arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
@roman_arabic = Hash[*roman.zip(arabic).flatten] | |
def arabic2roman(arabic) | |
roman = "" | |
@roman_arabic.each do |symbol,value| | |
while arabic/value > 0 | |
roman << symbol | |
arabic -= value | |
end | |
end | |
roman | |
end | |
def roman2arabic(roman) | |
arabic = 0 | |
while roman.size > 0 | |
current_char = @roman_arabic[roman[0..1]] ? roman[0..1] : roman[0] | |
arabic += @roman_arabic[current_char] | |
roman.sub!(current_char,'') | |
end | |
arabic | |
end | |
ARGF.each_line do |raw_line| | |
line = raw_line.chop! | |
break if line.empty? | |
line =~ /\A[0-9]+\z/ ? puts(arabic2roman(line.to_i)) : puts(roman2arabic(line)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment