Skip to content

Instantly share code, notes, and snippets.

@mxey
Created May 1, 2013 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxey/5496442 to your computer and use it in GitHub Desktop.
Save mxey/5496442 to your computer and use it in GitHub Desktop.
use v5.16;
use warnings;
use Test::More tests => 13;
sub to_roman {
my ($num) = @_;
my $out = '';
my @mapping = (
[ 10000 => 'Q' ],
[ 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' ],
);
while ( $num > 0 ) {
for (@mapping) {
my ( $decimal, $roman ) = @$_;
if ( $num >= $decimal ) {
$out .= $roman x ( $num / $decimal );
$num = $num % $decimal;
}
}
}
return $out;
}
is to_roman(1), "I";
is to_roman(2), "II";
is to_roman(3), "III";
is to_roman(4), "IV";
is to_roman(5), "V";
is to_roman(6), "VI";
is to_roman(7), "VII";
is to_roman(8), "VIII";
is to_roman(9), "IX";
is to_roman(10), "X";
# Wikipedia examples
is to_roman(1954), "MCMLIV";
is to_roman(1990), "MCMXC";
is to_roman(2008), "MMVIII";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment