Archive
Powershell ISE–Copy as html
Published a new project on codeplex for Powershell script to colored html conversion. This can be used to add a “copy as html” extension to the Powershell ISE. Hopefully it will save me some time the next time I reinstall my computer and, with a bit of luck, someone else find it useful too.
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…
Powershell: 99 bottles of beer
Trying out code golf challenge of 99 bottles of beer in Powershell.
$a=" bottles of beer";$b=" on the wall";$c=$a.remove(7,1)
99..2|%{"$_$a$b, $_$a.`nTake one down and pass it around, $($_-1)$a$b.`n"}
"1$c$b, 1$c.`nGo to the store and buy some more, 99$a$b."
192 characters (or 190 if written on one line using semi colon as delimiter). Still far from the best Perl script that only requires 151 characters (impressive).
I added a char count command to the Powershell ISE by adding the following lines to the ISE profile:
$addonsmenu = $psISE.CurrentPowerShellTab.AddOnsMenu
$addonsmenu.Submenus.Clear()
$addonsmenu.Submenus.Add("Count chars", { $psISE.CurrentFile.Editor.Text.Length }, "Ctrl+Alt+L") | Out-Null