Created
December 1, 2012 17:21
-
-
Save sway/4183333 to your computer and use it in GitHub Desktop.
SP Ruby quiz - Task 1
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
$map = { | |
'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 is_int?(s) | |
s =~ /^-?[0-9]+$/ | |
end | |
def to_arabic(s) | |
output = 0 | |
$map.each do |k, v| | |
while s.start_with?(k) | |
output += v | |
s.slice!(k) | |
end | |
end | |
return output | |
end | |
def to_roman(i) | |
output = "" | |
$map.each do |k, v| | |
while i >= v | |
output << k | |
i -= v | |
end | |
end | |
return output | |
end | |
while input = gets | |
if is_int?(input) | |
puts to_roman(input.to_i) | |
else | |
puts to_arabic(input) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one! Hard-coding the combinations seems to save a lot of code ...