Skip to content

Instantly share code, notes, and snippets.

@npras
Created July 3, 2012 07:14
Show Gist options
  • Save npras/3038220 to your computer and use it in GitHub Desktop.
Save npras/3038220 to your computer and use it in GitHub Desktop.
Ruby Challenge 5: Roman Numerals
# http://www.therubygame.com/challenges/5/submissions
# = 1
# V = 5
# X = 10
# L = 50
# C = 100
# D = 500
# M = 1000
# Sample i/o:
# MCMXCIX gives 1999, MMXII gives 2012
def to_arabic(roman)
f = false
o = 0
k = { :I => 1,
:V => 5,
:X => 10,
:L => 50,
:C => 100,
:D => 500,
:M => 1000}
0.upto(roman.length - 1) do |x|
if f; f = false;next; end
if (roman[x+1] != nil) && (k[roman[x].to_sym] < k[roman[x+1].to_sym])
o += (k[roman[x+1].to_sym] - k[roman[x].to_sym])
f = true
else
o += k[roman[x].to_sym]
end
end
o
end
puts to_arabic "XXIV"
puts to_arabic "MMXII" # 2012
puts to_arabic "XXIV" # 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment