Skip to content

Instantly share code, notes, and snippets.

@bbwharris
Created August 16, 2012 04:12
Show Gist options
  • Save bbwharris/3366741 to your computer and use it in GitHub Desktop.
Save bbwharris/3366741 to your computer and use it in GitHub Desktop.
Naive Inaccurate to_roman
# Doubt 100% accurate answer, but seems somewhat correct.
TRANSLATOR = {
1000 => 'M',
900 => 'CM',
500 => 'D',
400 => 'CD',
100 => 'C',
90 => 'XC',
50 => 'L',
40 => 'XL',
10 => 'X',
9 => 'IX',
5 => 'V',
4 => 'IV',
1 => 'I',
}
def to_roman(number)
result = ''
# Iterate through the translator, assuming we are in an ordered hash (ruby 1.9+)
# Order is important, must start with largest value and work down to lowest value
TRANSLATOR.each do |arabic_value, roman_numeral|
divisor = number / arabic_value
result += roman_numeral * divisor
# next iteration should set the number to the remainder
number = number % arabic_value
end
return result
end
#Simple Test:
(1..3999).each do |num|
puts "#{num} as a roman numeral: #{to_roman(num)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment