-
-
Save anonymous/a23b71515bc009a775b7 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
use common::sense; | |
say to_roman(5); #V | |
say to_roman(18); #XVIII | |
sub to_roman { | |
state $pairs = [ | |
[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'], | |
]; | |
#add 1 so it's possible to use a single comparison | |
my $number = (shift) + 1; | |
my $roman; | |
#convert negative to positive | |
$number *= - 1 if $_[0] < 0; | |
for (@$pairs) { | |
while ($number > $_->[0]) { | |
$roman .= $_->[1]; | |
$number -= $_->[0]; | |
} | |
} | |
return $roman; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment