Solving ActionScript Puzzlers in PowerShell

by Doug Finke on January 20, 2010

in ActionScript, PowerShell, Puzzlers

Andy Bryant has some ActionScript Puzzlers over here. So, let’s try them in PowerShell.

So the question is what does the call to loopy() return?

The answer is BEE,BOP,BOP,BOO. The extra BOP is the same result as the ActionScript and the same reason:

Although it appears that caps is defined only within the for loop, it is actually defined at the scope of the function. Therefore for the second null in the array, caps was not overwritten, but instead retained its value from the previous iteration of the loop.

Function loopy {
    $names = $null, "bee", "bop", $null, "boo"
    $result = @()            

    $names | % {
        if($_) {
            $caps = $_.ToUpper()
        }            

        if($caps) {
            $result+=$caps
        }
    }            

    $result -join ","
}            

loopy

Good stuff. Hope to get more time to check out the other puzzles. If you add $caps = “” before the first if statement the extra BOP is solved.

{ 3 comments… read them below or add one }

1 Paul Chavez 01.21.10 at 12:26 pm

This looked suspiciously like a quick ‘zip’ function I wrote last night so I tried to see if the issue applied to my logic. It doesn’t act exactly the same but is still odd. Here is a sample:
——-
function loopy2
{

$names = “abc”,”def”
$names2 = “def”,”ghi”
$result = @()
$names2 | ForEach-Object {
$name = $_
$f = $names | ?{ $_ -eq $name }

if ($f) { $result += $f.ToUpper() }
else { $result += $f }
}
$result.count
}
——-
I output the count property of the array because if it worked correctly you’d expect one item in the array, but really there ends up being two. However the second value is empty string or $null or something, not “def” as you might expect from the puzzle results.

2 Doug Finke 01.21.10 at 5:06 pm

I believe the second time thru when searching for $name and the value is not found, $f is -eq $null. This gets appended to your $result array, causing the count ot be 2.

You can check it like this: $result[1] -eq $null

3 Paul Chavez 01.22.10 at 12:17 pm

I see, in your example you don’t have an else statement when checking for existence of $caps. Since I have the else something gets added to $result in any case.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>