Created
August 16, 2012 04:12
-
-
Save bbwharris/3366741 to your computer and use it in GitHub Desktop.
Naive Inaccurate to_roman
This file contains hidden or 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
# 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