-
-
Save mmueller/abd3e4bf351d53188be422916b2441d3 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
#!/usr/bin/env ruby | |
module RomanNumeral | |
BRUTE_VALUE_MAP = { | |
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 | |
remainder = self | |
result = '' | |
pairs = BRUTE_VALUE_MAP.to_a.sort.reverse | |
pairs.each do |value, numeral| | |
while remainder >= value | |
result += numeral | |
remainder -= value | |
end | |
end | |
result | |
end | |
end | |
class Fixnum | |
include RomanNumeral | |
end | |
test_cases = { | |
1 => 'I', | |
2 => 'II', | |
3 => 'III', | |
4 => 'IV', | |
5 => 'V', | |
6 => 'VI', | |
7 => 'VII', | |
8 => 'VIII', | |
9 => 'IX', | |
10 => 'X', | |
50 => 'L', | |
100 => 'C', | |
500 => 'D', | |
1000 => 'M', | |
31 => 'XXXI', | |
148 => 'CXLVIII', | |
294 => 'CCXCIV', | |
312 => 'CCCXII', | |
421 => 'CDXXI', | |
528 => 'DXXVIII', | |
621 => 'DCXXI', | |
782 => 'DCCLXXXII', | |
870 => 'DCCCLXX', | |
911 => 'CMXI', | |
941 => 'CMXLI', | |
1043 => 'MXLIII', | |
1110 => 'MCX', | |
1226 => 'MCCXXVI', | |
1301 => 'MCCCI', | |
1485 => 'MCDLXXXV', | |
1509 => 'MDIX', | |
1607 => 'MDCVII', | |
1754 => 'MDCCLIV', | |
1832 => 'MDCCCXXXII', | |
1993 => 'MCMXCIII', | |
2074 => 'MMLXXIV', | |
2152 => 'MMCLII', | |
2212 => 'MMCCXII', | |
2343 => 'MMCCCXLIII', | |
2499 => 'MMCDXCIX', | |
2574 => 'MMDLXXIV', | |
2646 => 'MMDCXLVI', | |
2723 => 'MMDCCXXIII', | |
2892 => 'MMDCCCXCII', | |
2975 => 'MMCMLXXV', | |
3051 => 'MMMLI', | |
3185 => 'MMMCLXXXV', | |
3250 => 'MMMCCL', | |
3313 => 'MMMCCCXIII', | |
3408 => 'MMMCDVIII', | |
3501 => 'MMMDI', | |
3610 => 'MMMDCX', | |
3743 => 'MMMDCCXLIII', | |
3844 => 'MMMDCCCXLIV', | |
3888 => 'MMMDCCCLXXXVIII', | |
3940 => 'MMMCMXL', | |
3999 => 'MMMCMXCIX' | |
} | |
test_cases.each do |value, numeral| | |
result = value.to_roman | |
if result == numeral | |
puts "OK: #{value} -> #{result}" | |
else | |
puts "FAIL: #{value} -> #{result} (expected #{numeral})" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment