Skip to content

Instantly share code, notes, and snippets.

@pandiculator
Created December 29, 2015 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pandiculator/87ff9407716f55eb2460 to your computer and use it in GitHub Desktop.
Save pandiculator/87ff9407716f55eb2460 to your computer and use it in GitHub Desktop.
$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
"@
# 1.Split $list into a collection of entries, as you typed them,
# and sort the results by length. As a bonus, see if you can
# sort the length without the number.
$listEntries = $list -split "`n"
$listEntries | Sort-Object -Property Length
$listEntries -replace "[\d]+\s","" | Sort-Object -Property Length
# 2.Turn each line into a custom object with a properties for Count and Item.
$objColl = @()
for ($i = 0; $i -lt $listEntries.Length; $i++) {
$obj = [PSCustomObject] @{
Count = ($listEntries[$i] -split ' ',2)[0]
Item = ($listEntries[$i] -split ' ',2)[1]
} # End Object Creation
$objColl += $obj
} #End for
# 3.Using your custom objects, what is the total number of all bird-related items?
$birds = 'Partridge','Dove','Hen','Bird','Geese','Swan'
$sum = 0
foreach ($bird in $birds) {
foreach ($obj in $objColl) {
if ("$obj.Item" -match "$bird") {
$sum = $sum + $obj.Count
} #End if
} #End foreach $obj
} #End foreach $bird
Write-Output "Total number of bird related items is: $sum."
Write-Output "Total number of items is: $($objColl | Measure-Object -Property Count -Sum | Select-Object -ExpandProperty Sum)."
# Bonus: Using PowerShell what is the total number of cumulative gifts?
$cumSum = 0
for ($i = 0; $i -lt $objColl.Length; $i++) {
for ($j = 0; $j -le $i; $j++) {
$cumSum = $cumSum + $objColl[$j].Count
} #end for $j
} #end for $i
Write-Output "The total number of cumulative gifts is: $cumSum."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment