Advent of Code 2023
December 8, 2023

Introduction
I found out about the AdventOfCode on 2023-12-07. I thought I would have some fun, learn, and share. I started off doing only PowerShell solutions. I decided to go back and do Python solutions too. I skipped some best practices (e.g. exception handling) in these challenges. Please don’t beat me up too much for it :grin:.
Look at my Github Repo, if you want.
Day 1 - Puzzle 1 - PowerShell
<#
.DESCRIPTION
My PowerShell solution to the puzzle https://adventofcode.com/2023/day/1
Puzzle 1
.PARAMETER FilePath
The file path for the inpute file
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$FilePath='.\day1-puzzle1-input.txt'
)
[string]$FirstNumber = ''
[string]$SecondNumber = ''
[uint32]$TheNumber = 0
[uint32]$SumNumbers = 0
[uint32]$tmp = 0
$Numbers = New-Object System.Collections.ArrayList
foreach ($line in (Get-Content $FilePath)) {
$FirstNumber = ''
$SecondNumber = ''
$TheNumber = 0
for ($i = 0; $i -lt $line.Length; $i++) {
if ([uint32]::TryParse($line[$i], [ref]$tmp)) {
$Numbers.Add($line[$i]) | Out-Null
}
}
$FirstNumber = $Numbers[0]
$SecondNumber = $Numbers[$Numbers.Count-1]
Write-Verbose $FirstNumber
Write-Verbose $SecondNumber
$SumNumbers += ([uint32]::Parse(($FirstNumber + $SecondNumber)))
$Numbers.Clear()
}
Write-Output $SumNumbersDay 1 - Puzzle 1 - Python
'''
.DESCRIPTION
My Python solution to the puzzle https://adventofcode.com/2023/day/1
Puzzle 1
'''
file_path: str = 'day1-puzzle-input.txt'
first_number: str = ''
second_number: str = ''
the_number: int = 0
sum_numbers: int = 0
tmp: int = 0
num_list: list = []
with open(file_path) as file:
lines = file.readlines()
for line in lines:
first_number = ''
second_number = ''
the_number = 0
for i in range(len(line)):
if str.isnumeric(line[i]):
num_list.append(line[i])
first_number = num_list[0] # first element
second_number = num_list[-1] # last element
the_number = int(first_number + second_number)
sum_numbers += the_number
num_list.clear()
print(sum_numbers)Day 1 - Puzzle 1 - HTML/JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Day 1 - Puzzle 1 - HTML/JS</title>
<script>
function bodyOnload() {
document.getElementById('fileName')
.addEventListener('change', function () {
let fileReader = new FileReader();
fileReader.onload = function () {
document.getElementById('fileOutput')
.textContent = fileReader.result;
}
fileReader.readAsText(this.files[0]);
})
}
function btnPush() {
let fileOutput = document.getElementById('fileOutput')
.innerText.split("\r\n")
let answer = document.getElementById('answer');
let numbers = [];
let sumNumbers = 0;
for (let i = 0; i < fileOutput.length; i++) {
let line = fileOutput[i];
for (let i2 = 0; i2 < line.length; i2++) {
// check if we have a number
if (isNaN(line[i2]) == false) {
numbers.push(line[i2]);
}
}
let firstNumber = numbers[0];
let secondNumber = numbers[numbers.length-1];
sumNumbers += Number(firstNumber + secondNumber);
numbers = [];
}
answer.innerText = sumNumbers;
return true;
}
</script>
<style>
.code {
font-family: 'Courier New', Courier, monospace;
background-color: gray;
}
#answer {
background-color: green;
color: lightskyblue;
}
</style>
</head>
<body onload="bodyOnload()">
<div>
<p>
<input title="File Name" type="file" name="fileName"
id="fileName" value="day1puzzle1.txt"> <br>
<button type="button" id="btn1" name="btn1" value="Submit"
onclick="btnPush()">Calculate</button>
</p>
</div>
<div>
<p id="answer"></p>
</div>
<div class="code">
<pre id="fileOutput"></pre>
</div>
</body>
</html>Day 1 - Puzzle 2 - PowerShell
<#
.DESCRIPTION
My PowerShell solution to the puzzle https://adventofcode.com/2023/day/1
Puzzle 2
.PARAMETER FilePath
The file path for the inpute file
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$FilePath='.\day1-puzzle1-input.txt'
)
[string]$FirstNumber = ''
[string]$SecondNumber = ''
[uint32]$TheNumber = 0
[uint32]$SumNumbers = 0
[uint32]$tmp = 0
$WordNums = @{
'one'='1';
'two'='2';
'three'='3';
'four'='4';
'five'='5';
'six'='6';
'seven'='7';
'eight'='8';
'nine'='9';
}
$o = New-Object PSObject -Property @{Number=''; Position=0;}
$NumList = New-Object System.Collections.ArrayList
foreach ($line in (Get-Content $FilePath)) {
$FirstNumber = ''
$SecondNumber = ''
$TheNumber = 0
foreach ($WordNum in $WordNums.Keys) {
[int16]$pos = $line.IndexOf($WordNum)
while ($pos -gt -1) {
$o.Number = $WordNums[$WordNum]
$o.Position = $pos
$NumList.Add($o.PSObject.Copy())
$pos = $line.IndexOf($WordNum, $pos+1)
}
}
for ($i = 0; $i -lt $line.Length; $i++) {
if ([uint32]::TryParse($line[$i], [ref]$tmp)) {
$o.Number = $line[$i].ToString()
$o.Position = $i
$NumList.Add($o.PSObject.Copy()) | Out-Null
}
}
$Sorted = $NumList | Sort-Object Position
$FirstNumber = $Sorted[0].Number
$SecondNumber = $Sorted[$Sorted.Count-1].Number
Write-Verbose $FirstNumber
Write-Verbose $SecondNumber
$SumNumbers += ([uint32]::Parse(($FirstNumber + $SecondNumber)))
$NumList.Clear()
}
Write-Output $SumNumbersDay 1 - Puzzle 2 - Python
'''
.DESCRIPTION
My Python solution to the puzzle https://adventofcode.com/2023/day/1
Puzzle 2
'''
from dataclasses import dataclass
@dataclass(order=True)
class Numbers:
number: str
position: int
file_path: str = 'day1-puzzle-input.txt'
first_number: str = ''
second_number: str = ''
the_number: int = 0
sum_numbers: int = 0
tmp: int = 0
num_list: list = []
word_nums: dict = {
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9'
}
with open(file_path) as file:
lines = file.readlines()
for line in lines:
first_number = ''
second_number = ''
the_number = 0
for i in word_nums:
pos: int = line.find(i)
while (pos > -1): # keep finding the number until you can't
num_list.append(Numbers(word_nums[i], pos))
pos = line.find(i, pos+1)
for i in range(len(line)):
if str.isnumeric(line[i]):
num_list.append(Numbers(line[i], i))
# create a sorted list (lowest to highest) by position in the string
sorted_nums = sorted(num_list, key=lambda n: n.position)
first_number = sorted_nums[0].number# first element
second_number = sorted_nums[-1].number # last element
the_number = int(first_number + second_number)
sum_numbers += the_number
num_list.clear()
print(sum_numbers)Day 2 - Puzzle 1 - PowerShell
<#
.DESCRIPTION
My PowerShell solution to the puzzle https://adventofcode.com/2023/day/2
Puzzle 1
.PARAMETER FilePath
The file path for the input file
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$FilePath='.\day2-puzzle-input.txt'
)
[uint16]$RedCubesReq = 12
[uint16]$GreenCubesReq = 13
[uint16]$BlueCubesReq = 14
[string]$BlockSetSplitCh = ';'
[string]$BlockSplitCh = ','
[string]$BeginLineCh = ':'
$o = New-Object PSObject -Property @{id=0; red=0; blue=0; green=0;}
[string]$GameMatch = '^Game\W+(?<GameID>\d+)\:'
[string]$BlockMatch = '^(?<NumBlocks>\d+)\W+(?<BlockColor>red|blue|green)'
[uint32]$GameSum = 0
foreach ($line in (Get-Content $FilePath)) {
if ($line -match $GameMatch) {
$o.id = $Matches['GameID']
}
else {
Write-Error "The GameID did not match for line: $($line)"
}
[string]$line2 = $line.SubString($line.IndexOf($BeginLineCh)+1)
[string[]]$BlockSets = $line2.Split($BlockSetSplitCh)
$BlockArray = @()
foreach ($Draw in $BlockSets) {
$o.red = 0
$o.green = 0
$o.blue = 0
[string[]]$Blocks = $Draw.Split($BlockSplitCh)
foreach ($Block in $Blocks) {
if ($Block.Trim() -match $BlockMatch) {
switch ($Matches['BlockColor']) {
'red' {$o.red = [uint16]::Parse($Matches['NumBlocks'])}
'green' {$o.green = [uint16]::Parse($Matches['NumBlocks'])}
'blue' {$o.blue = [uint16]::Parse($Matches['NumBlocks'])}
Default {Write-Error "Invalid block color: $($Matches['BlockColor'])"}
}
}
else {
Write-Error "Bad Block Color Match on: $($Block)"
}
}
$BlockArray += $o.PSObject.Copy()
}
$TooManyBlocks = $BlockArray | Where-Object {
$_.red -gt $RedCubesReq -or
$_.blue -gt $BlueCubesReq -or
$_.green -gt $GreenCubesReq}
if ($TooManyBlocks) {
Write-Information "Skipped GameID: $($o.id)"
}
else {
$GameSum += $o.id
}
}
Write-Output $GameSumDay 2 - Puzzle 2 - PowerShell
<#
.DESCRIPTION
My PowerShell solution to the puzzle https://adventofcode.com/2023/day/2
Puzzle 2
.PARAMETER FilePath
The file path for the inpute file
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$FilePath='.\day2-puzzle-input.txt'
)
[string]$BlockSetSplitCh = ';'
[string]$BlockSplitCh = ','
[string]$BeginLineCh = ':'
$o = New-Object PSObject -Property @{id=0; red=0; blue=0; green=0;}
[string]$GameMatch = '^Game\W+(?<GameID>\d+)\:'
[string]$BlockMatch = '^(?<NumBlocks>\d+)\W+(?<BlockColor>red|blue|green)'
[uint32]$GameSum = 0
[uint16]$MinRedBlocks = 0
[uint16]$MinBlueBlocks = 0
[uint16]$MinGreenBlocks = 0
$BlockArray = @()
foreach ($line in (Get-Content $FilePath)) {
if ($line -match $GameMatch) {
$o.id = $Matches['GameID']
}
else {
Write-Error "The GameID did not match for line: $($line)"
}
[string]$line2 = $line.SubString($line.IndexOf($BeginLineCh)+1)
[string[]]$BlockSets = $line2.Split($BlockSetSplitCh)
$BlockArray.Clear()
$MinRedBlocks = 0
$MinGreenBlocks = 0
$MinBlueBlocks = 0
foreach ($Draw in $BlockSets) {
$o.red = 0
$o.green = 0
$o.blue = 0
[string[]]$Blocks = $Draw.Split($BlockSplitCh)
foreach ($Block in $Blocks) {
if ($Block.Trim() -match $BlockMatch) {
switch ($Matches['BlockColor']) {
'red' {$o.red = [uint16]::Parse($Matches['NumBlocks'])}
'green' {$o.green = [uint16]::Parse($Matches['NumBlocks'])}
'blue' {$o.blue = [uint16]::Parse($Matches['NumBlocks'])}
Default {Write-Error "Invalid block color: $($Matches['BlockColor'])"}
}
}
else {
Write-Error "Bad Block Color Match on: $($Block)"
}
}
$BlockArray += $o.PSObject.Copy()
}
# Determine minimum blocks (assuming all colors will have at least 1 block)
$MinRedBlocks = ($BlockArray | Measure-Object -Property red -Maximum).Maximum
$MinGreenBlocks = ($BlockArray | Measure-Object -Property green -Maximum).Maximum
$MinBlueBlocks = ($BlockArray | Measure-Object -Property blue -Maximum).Maximum
# Calculate product of minimum blocks and add it to the sum of Games
$GameSum += ($MinRedBlocks * $MinGreenBlocks * $MinBlueBlocks)
}
Write-Output $GameSum