Created
October 6, 2010 15:39
-
-
Save seanhandley/613542 to your computer and use it in GitHub Desktop.
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
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