Write a script to encode decimal numbers into Roman numerals and decode Roman numerals back to decimal numbers.
Logic
We define a mapping list/dictionary of the core values (including combined subtractive pairs like `CM`, `IV`, `IX`). For encoding, we repeatedly subtract the largest possible values while prefixing their corresponding Roman characters. For decoding, we match Roman prefix patterns sequentially and add their corresponding numerical values.
ch-1.pl
sub encode_roman {
my $number = shift;
my @roman_map = (
[ 'M', 1000 ], [ 'CM', 900 ], [ 'D', 500 ], [ 'CD', 400 ],
[ 'C', 100 ], [ 'XC', 90 ], [ 'L', 50 ], [ 'XL', 40 ],
[ 'X', 10 ], [ 'IX', 9 ], [ 'V', 5 ], [ 'IV', 4 ],
[ 'I', 1 ]
);
my $roman_numeral = '';
foreach my $pair (@roman_map) {
my ( $numeral, $value ) = @$pair;
while ( $number >= $value ) {
$roman_numeral .= $numeral;
$number -= $value;
}
}
return $roman_numeral;
}
sub decode_roman {
my $roman_numeral = shift;
my @roman_map = (
[ 'M', 1000 ], [ 'CM', 900 ], [ 'D', 500 ], [ 'CD', 400 ],
[ 'C', 100 ], [ 'XC', 90 ], [ 'L', 50 ], [ 'XL', 40 ],
[ 'X', 10 ], [ 'IX', 9 ], [ 'V', 5 ], [ 'IV', 4 ],
[ 'I', 1 ]
);
my $number = 0;
foreach my $pair (@roman_map) {
my ( $numeral, $value ) = @$pair;
while ( $roman_numeral =~ /^$numeral/ ) {
$number += $value;
$roman_numeral =~ s/^$numeral//;
}
}
return $number;
}
ch-1.py
roman_map = {
"I": 1, "IV": 4, "V": 5, "IX": 9, "X": 10, "XL": 40, "L": 50,
"XC": 90, "C": 100, "CD": 400, "D": 500, "CM": 900, "M": 1000,
}
def encode_to_roman(number):
result = ""
for roman, value in sorted(roman_map.items(), key=lambda x: -x[1]):
while number >= value:
result += roman
number -= value
return result
def decode_to_decimal(roman):
result = 0
index = 0
while index < len(roman):
if index < len(roman) - 1 and roman[index : index + 2] in roman_map:
result += roman_map[roman[index : index + 2]]
index += 2
else:
result += roman_map[roman[index]]
index += 1
return result