Home > Uncategorized > Powershell: convert roman numbers to decimal

Powershell: convert roman numbers to decimal

I picked up another code golf challenge. This time the task was to convert roman numbers to decimal numbers. Here is my result (~132 characters, function header excluded):

function Convert-RomanToDecimal($s)
{
    $t=@{I=1;V=5;X=10;L=50;C=100;D=500;M=1000}
    1..$s.Length|%{$x=$m=0}{$i=$t[[string]$s[$_]];if($i-lt$m){$x-=$i}else{$x+=$i;$m=$i}}{$x}
}

Along with my test cases:

$testdata = @{
    # wikipedia
    "MCMXLIV" = 1944;
    # code golf test cases
    "MMMCCXC" = 3290;
    "MCMVII" = 1907;
    "MMCDXLVII" = 2447;
    "MMCMLXXXIV" = 2984;
    "MXCVI" = 1096;
    "MCMIV" = 1904;
    "MMDII" = 2502;
    "M" = 1000;
    "MMDLXXIX" = 2579;
    "MMMLXXXVIII" = 3088;
    "MMDCCXCIX" = 2799;
    "MMDVI" = 2506;
    "MMMDCCLVII" = 3757;
    "MMMCCLXXXIII" = 3283;
    "MCDXL" = 1440;
    "MMD" = 2500;
    "DCLI" = 651;   
}
   
$testdata.keys | % {
    $calculated = Convert-RomanToDecimal $_
    $expected = $testdata[$_]
    if ($calculated -ne $expected) {
        throw "Test failed since $calculated does not match $expected"
    }   
}

I guess it is not too hard to cut it down a bit further (or is it?). Anyway – I like the compactness of Powershell. Of course – when pushed this far – the result gets, erhmm, somewhat obfuscated…

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: