Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Created October 6, 2010 15:39
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 seanhandley/613542 to your computer and use it in GitHub Desktop.
Save seanhandley/613542 to your computer and use it in GitHub Desktop.
class Roman
Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
def initialize(i)
@i = i
end
def to_s
roman(@i)
end
def roman(num)
return Symbols[num] if Symbols.has_key?(num)
return '' if num <= 0
Subtractors.each do |cut_point, subtractor|
return roman(cut_point) + roman(num - cut_point) if num > cut_point
return roman(subtractor) + roman(num + subtractor) if num >= cut_point - subtractor and num < cut_point
end
end
end
if __FILE__ == $0
num = 8879
puts "Arabic #{num} in Roman numerals is #{Roman.new(num).to_s}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment