Created
March 25, 2012 11:19
-
-
Save basgys/2192992 to your computer and use it in GitHub Desktop.
Roman to Arabic number converter
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
input = "MCMXCIX" # 1999 | |
# Roman to Arabic mapper | |
r2a = {"I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000} | |
# Translate input to an array of arabic numbers | |
numbers = input.split(//).map {|c| r2a[c]} | |
count = numbers.count-1 | |
# Compute result (more infos @ http://en.wikipedia.org/wiki/Roman_numerals) | |
result = 0 | |
(0..count).each do |i| | |
if i != count and numbers[i] < numbers[i+1] | |
result -= numbers[i] | |
else | |
result += numbers[i] | |
end | |
end | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment