Sep 15 2013   3:44AM GMT

# PowerShell whimsy with arrays

Profile: Richard Siddaway

I was thinking about the Christmas song – 12 days of Christmas and wondering just how many presents were delivered. Don’t ask why!

So I decided to work it out.

\$days = 12
\$presents = 1..\$days

\$total = 0
0..(\$days-1) | foreach {
\$total += \$presents[\$_] * \$presents[(-1 * \$presents[\$_] )]
}
\$total

You start with 12 days & create an array containing the values 1 to 12

Set the total to 0 & loop through the days. Because array indices start at 0 you need the range 0-11 which you can calculate as 0..(\$days-1)

The total number of presents delivered of a type is the number of things 1 partridge, 2 turtle doves etc multiplied by the number of times its delivered 12, 11, 10 etc

The number of presents of a particular type is from the array \$presents[\$_]. The days delivered is found by getting an inverse relationship into the array. So present 1 delivered 12 times which is value of last element; present 2 delivered 11 times which is next to last element etc.

Now the point of the post is to show you that you can access the last element of an array using an index of –1; the next to last using –2 and so on.

As we want to calculate this we end up with taking the value of the array for that point and multiplying by –1 to get the value we need fo r the multiplication

\$presents[(-1 * \$presents[\$_] )]

Add the calculated values together and you get the total number of presents delivered.

I’ve deliberately put more () into this than needed to make the logic easier to follow.