## 2015 December Scripting Games Puzzle

The December 2015 puzzle was based on the 12 Days of Christmas song.  Starting with this here-string.

\$list = @"
1 Partridge in a pear tree
2 Turtle Doves
3 French Hens
4 Calling Birds
5 Golden Rings
6 Geese a laying
7 Swans a swimming
8 Maids a milking
10 Lords a leaping
11 Pipers piping
12 Drummers drumming
"@

A here-string is a multiline string. It is NOT an array – its a single string. The first task is to  split into an array of individual lines:

## split into individual lines
\$s = \$list -split '\n'

Each line of the multiline here string ends with a new line – so that becomes the split point.

The array can be sorted by length of line. Ascending or descending wasn’t specified so here’s both options:

'Sort by length ascending'
\$s | Sort-Object -Property Length

"`n "
'sort by length descending'
\$s | Sort-Object -Property Length -Descending

Removing the numbers to give justthe text and sorting by length of text. I trmmed the strings as some empty spaces had appeared in the arrays. I think because I copied the here-string

"`n "
'remove numbers sort by length ascending'
\$s.Trim() -replace '\d{1,2}\s', '' | Sort-Object -Property Length #| group length | ft -a -wrap

"`n "
'remove numbers sort by length descending'
\$s.Trim() -replace '\d{1,2}\s', '' | Sort-Object -Property Length -Descending

Create objects. Split on white space and restrict output to 2 elements – number and text in this case. Create object using New-object

"`n "
#'create objects'
\$items = @()
\$s.Trim() | foreach {
\$item =  \$psitem -split '\s',2
\$items += New-Object -TypeName PSObject -Property @{
Count = \$item[0] -as [int]
Item = \$item[1]
}
}

Count the number of birds

"`n "
'count of birds'
\$birdcount = (\$items -match '(Partridge|Doves|Hens|Birds|Geese|Swans)' | Measure-Object -Property Count -Sum).Sum
\$birdcount

Count all items

"`n "
'count of items'
\$itemcount = (\$items | Measure-Object -Property Count -Sum).Sum
\$itemcount

If you treat the song as stating the gifts are cumulative then how many gifts are given in total.  Each item is given (13 – the day on which its given) times i.e. 12 to 1 times respectively.  The total number of items can be calculated like this

"`n "
'cumulative count of items'
\$total = 0
\$items | foreach {\$total += \$psitem.Count * (13-\$psitem.Count) }
\$total

As a bonus here’s how you calculate the cumulative number of each type of item.

"`n "
'cumulative number of each item'
\$totalitems =@()
\$items | foreach {
\$totalitems += New-Object -TypeName PSObject -Property @{
Count = \$psitem.Count * (13-\$psitem.Count)
Item = \$psitem.Item
}
}
\$totalitems