Skip to content

Instantly share code, notes, and snippets.

@basgys
Created March 25, 2012 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basgys/2192992 to your computer and use it in GitHub Desktop.
Save basgys/2192992 to your computer and use it in GitHub Desktop.
Roman to Arabic number converter
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