Skip to content

Instantly share code, notes, and snippets.

@brianbunke
Last active December 8, 2015 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianbunke/ea95576fdc978b2bc6bf to your computer and use it in GitHub Desktop.
Save brianbunke/ea95576fdc978b2bc6bf to your computer and use it in GitHub Desktop.
2015-12 PowerShell Scripting Games Puzzle
$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
9 Ladies dancing
10 Lords a leaping
11 Pipers piping
12 Drummers drumming
'@
### 1a: Split $list into a collection of entries, as you typed them, and sort the results by length.
# `n is PowerShell's special character to denote "new line." Split up the entries by line, then sort
$List -split "`n" | Sort Length -Descending
### 1b: As a bonus, see if you can sort the length without the number.
# You can sort a custom expression (Get-Help Sort-Object -Full)
# Use RegEx (https://regex101.com) to replace the # and space with nothing, then sort that
$List -split "`n" | Sort {$_ -replace '\d+\s','' | Select -ExpandProperty Length} -Descending
### 2: Turn each line into a custom object with a properties for Count and Item.
# Define an empty array; append each of the twelve objects into one variable
$ListObjects = @()
$List -split "`n" | ForEach-Object {
# Ordered for no good reason; [int] so I can sum Count later
$Properties = [ordered]@{'Count' = [int]($_ -split ' ' | Select -First 1)
'Item' = $_ -replace '\d+\s',''
}
$ListObjects += New-Object -TypeName PSObject -Property $Properties
}
$ListObjects
### 3: Using your custom objects, what is the total number of all bird-related items?
# I'll spare everyone the mess I had here prior (hint: -like -or -like -or -like -or ...)
# Shamelessly stolen from previous solutions (how cool is "|" on the -match here?!)
$ListObjects | Where {$_.Item -match 'Partridge|Dove|Hen|Bird|Geese|Swan'} | Measure-Object -Property Count -Sum | Select -ExpandProperty Sum
### 4: What is the total count of all items?
$ListObjects | Measure-Object -Property Count -Sum | Select -ExpandProperty Sum
### BONUS: Using PowerShell what is the total number of cumulative gifts?
# https://en.wikipedia.org/wiki/Tetrahedral_number
# Which led me to:
# http://mathlesstraveled.com/2006/12/22/computing-tetrahedral-numbers/
# tl;dr - Triangular numbers (1, 1+2, 1+2+3, etc.) to 12, and then sum it up
$ListObjects | ForEach-Object {
# For each object in $ListObject (12), we want to append the triangular number to the running $GiftTotal
# By nesting a second ForEach, it will be 1+1+2+1+2+3+1+2+3+4...
(1..$_.Count) | ForEach-Object {
$Te12 += $_
}
}
$Te12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment