Skip to content

Instantly share code, notes, and snippets.

@manualbashing
Last active December 7, 2023 15:09
Show Gist options
  • Save manualbashing/90d0de8432502361385dbdd075200bd0 to your computer and use it in GitHub Desktop.
Save manualbashing/90d0de8432502361385dbdd075200bd0 to your computer and use it in GitHub Desktop.
function Import-PuzzleInput {
param (
$Path
)
$puzzleInput = Get-Content $Path
$puzzleInput -replace '.*:' | ForEach-Object {
$scratchCardNumbers, $null, $numbersYouHave = $_ -replace ' +', ' ' -split '( \| )'
$scratchCardNumbers = $scratchCardNumbers -split ' '
$numbersYouHave = $numbersYouHave -split ' '
$winningNumbers = Compare-Object $scratchCardNumbers $numbersYouHave -IncludeEqual -ExcludeDifferent
[PSCustomObject]@{
ScratchCardNumbers = $scratchCardNumbers
NumbersYouHave = $numbersYouHave
NumberOfMatches = $winningNumbers.Length
InstanceCount = 1
}
}
}
function Get-WinningPoints {
param (
[Parameter(ValueFromPipeline)]
$InputObject
)
Begin {
$sum = 0
}
Process {
foreach ($item in $InputObject) {
if ($winningNumbers) {
$points = [math]::Pow(2, $item.NumberOfMatches - 1)
$sum += $points
}
}
}
End {
Write-Output $sum
}
}
function Get-CardCopies {
param (
$InputObject
)
$scratchCards = $InputObject
for ($i = 0; $i -lt $scratchCards.Count; $i++) {
if ($scratchCards[$i].NumberOfMatches -eq 0) {
continue
}
$copyStart = $i + 1
$copyEnd = $i + $scratchCards[$i].NumberOfMatches
$copyRange = $copyStart .. $copyEnd | Where-Object { $_ -lt $scratchCards.Length }
foreach ($copyIndex in $copyRange) {
$cardToCopy = $scratchCards[$copyIndex]
$cardToCopy.InstanceCount += $scratchCards[$i].InstanceCount
}
}
Write-Output $scratchCards
}
$puzzleInput = Import-PuzzleInput $PSScriptRoot/input.txt
# Part 1
$puzzleInput | Get-WinningPoints
# Part 2
Get-CardCopies $puzzleInput | Measure-Object -Property InstanceCount -Sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment