Advent of Code 2023

advent-of-code-2023.webp

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 😁.

Look at my Github Repo, if you want.

Day 1 - Puzzle 1 - PowerShell

 1<#
 2.DESCRIPTION
 3My PowerShell solution to the puzzle https://adventofcode.com/2023/day/1
 4Puzzle 1
 5
 6.PARAMETER FilePath
 7The file path for the inpute file
 8#>
 9
10[CmdletBinding()]
11param (
12    [Parameter(Mandatory=$false)]
13    [string]$FilePath='.\day1-puzzle1-input.txt'
14)
15
16[string]$FirstNumber = ''
17[string]$SecondNumber = ''
18[uint32]$TheNumber = 0
19[uint32]$SumNumbers = 0
20[uint32]$tmp = 0
21$Numbers = New-Object System.Collections.ArrayList
22foreach ($line in (Get-Content $FilePath)) {
23    $FirstNumber = ''
24    $SecondNumber = ''
25    $TheNumber = 0
26
27    for ($i = 0; $i -lt $line.Length; $i++) {
28        if ([uint32]::TryParse($line[$i], [ref]$tmp)) {
29            $Numbers.Add($line[$i]) | Out-Null
30        }
31    }
32    $FirstNumber = $Numbers[0]
33    $SecondNumber = $Numbers[$Numbers.Count-1]
34    Write-Verbose $FirstNumber
35    Write-Verbose $SecondNumber
36    $SumNumbers += ([uint32]::Parse(($FirstNumber + $SecondNumber)))
37    $Numbers.Clear()
38}
39
40Write-Output $SumNumbers

Day 1 - Puzzle 1 - Python

 1'''
 2.DESCRIPTION
 3My Python solution to the puzzle https://adventofcode.com/2023/day/1
 4Puzzle 1
 5'''
 6file_path: str = 'day1-puzzle-input.txt'
 7first_number: str = ''
 8second_number: str = ''
 9the_number: int = 0
10sum_numbers: int = 0
11tmp: int = 0
12num_list: list = []
13
14with open(file_path) as file:
15    lines = file.readlines()
16    for line in lines:
17        first_number = ''
18        second_number = ''
19        the_number = 0
20        
21        for i in range(len(line)):
22            if str.isnumeric(line[i]):
23                num_list.append(line[i])
24
25        first_number = num_list[0] # first element
26        second_number = num_list[-1] # last element
27        the_number = int(first_number + second_number)
28        sum_numbers += the_number
29        num_list.clear()
30
31print(sum_numbers)

Day 1 - Puzzle 1 - HTML/JS

 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4    <meta charset="utf-8">
 5    <meta name="viewport" content="width=device-width, initial-scale=1">
 6    <title>Day 1 - Puzzle 1 - HTML/JS</title>
 7    <script>
 8        function bodyOnload() {
 9            document.getElementById('fileName')
10                .addEventListener('change', function () {
11                    let fileReader = new FileReader();
12                    fileReader.onload = function () {
13                        document.getElementById('fileOutput')
14                            .textContent = fileReader.result;
15                    }
16
17                    fileReader.readAsText(this.files[0]);
18                })
19        }
20
21        function btnPush() {
22            let fileOutput = document.getElementById('fileOutput')
23                .innerText.split("\r\n")
24            let answer = document.getElementById('answer');
25            let numbers = [];
26            let sumNumbers = 0;
27            for (let i = 0; i < fileOutput.length; i++) {
28                let line = fileOutput[i];
29                for (let i2 = 0; i2 < line.length; i2++) {
30                    // check if we have a number
31                    if (isNaN(line[i2]) == false) {
32                        numbers.push(line[i2]);
33                    }
34                }
35                let firstNumber = numbers[0];
36                let secondNumber = numbers[numbers.length-1];
37                sumNumbers += Number(firstNumber + secondNumber);
38                numbers = [];
39            }
40
41            answer.innerText = sumNumbers;
42
43            return true;
44        }
45    </script>
46    <style>
47        .code {
48            font-family: 'Courier New', Courier, monospace;
49            background-color: gray;
50        }
51        #answer {
52            background-color: green;
53            color: lightskyblue;
54        }
55    </style>
56</head>
57<body onload="bodyOnload()">
58    <div>
59        <p>
60            <input title="File Name" type="file" name="fileName" 
61                id="fileName" value="day1puzzle1.txt"> <br>
62            <button type="button" id="btn1" name="btn1" value="Submit" 
63                onclick="btnPush()">Calculate</button>
64        </p>
65    </div>
66    <div>
67        <p id="answer"></p>
68    </div>
69    <div class="code">
70        <pre id="fileOutput"></pre>
71    </div>
72</body>
73</html>

Day 1 - Puzzle 2 - PowerShell

 1<#
 2.DESCRIPTION
 3My PowerShell solution to the puzzle https://adventofcode.com/2023/day/1
 4Puzzle 2
 5
 6.PARAMETER FilePath
 7The file path for the inpute file
 8#>
 9
10[CmdletBinding()]
11param (
12    [Parameter(Mandatory=$false)]
13    [string]$FilePath='.\day1-puzzle1-input.txt'
14)
15
16[string]$FirstNumber = ''
17[string]$SecondNumber = ''
18[uint32]$TheNumber = 0
19[uint32]$SumNumbers = 0
20[uint32]$tmp = 0
21$WordNums = @{
22    'one'='1';
23    'two'='2';
24    'three'='3';
25    'four'='4';
26    'five'='5';
27    'six'='6';
28    'seven'='7';
29    'eight'='8';
30    'nine'='9';
31}
32$o = New-Object PSObject -Property @{Number=''; Position=0;}
33$NumList = New-Object System.Collections.ArrayList
34foreach ($line in (Get-Content $FilePath)) {
35    $FirstNumber = ''
36    $SecondNumber = ''
37    $TheNumber = 0
38    foreach ($WordNum in $WordNums.Keys) {
39        [int16]$pos = $line.IndexOf($WordNum)
40        while ($pos -gt -1) {
41            $o.Number = $WordNums[$WordNum]
42            $o.Position = $pos
43            $NumList.Add($o.PSObject.Copy())
44            $pos = $line.IndexOf($WordNum, $pos+1)
45        }
46    }
47
48    for ($i = 0; $i -lt $line.Length; $i++) {
49        if ([uint32]::TryParse($line[$i], [ref]$tmp)) {
50            $o.Number = $line[$i].ToString()
51            $o.Position = $i
52            $NumList.Add($o.PSObject.Copy()) | Out-Null
53        }
54    }
55    $Sorted = $NumList | Sort-Object Position
56    $FirstNumber = $Sorted[0].Number
57    $SecondNumber = $Sorted[$Sorted.Count-1].Number
58    Write-Verbose $FirstNumber
59    Write-Verbose $SecondNumber
60    $SumNumbers += ([uint32]::Parse(($FirstNumber + $SecondNumber)))
61    $NumList.Clear()
62}
63
64Write-Output $SumNumbers

Day 1 - Puzzle 2 - Python

 1'''
 2.DESCRIPTION
 3My Python solution to the puzzle https://adventofcode.com/2023/day/1
 4Puzzle 2
 5'''
 6from dataclasses import dataclass
 7
 8@dataclass(order=True)
 9class Numbers:
10    number: str
11    position: int
12
13
14file_path: str = 'day1-puzzle-input.txt'
15first_number: str = ''
16second_number: str = ''
17the_number: int = 0
18sum_numbers: int = 0
19tmp: int = 0
20num_list: list = []
21word_nums: dict = {
22    'one': '1',
23    'two': '2',
24    'three': '3',
25    'four': '4',
26    'five': '5',
27    'six': '6',
28    'seven': '7',
29    'eight': '8',
30    'nine': '9'
31}
32
33with open(file_path) as file:
34    lines = file.readlines()
35    for line in lines:
36        first_number = ''
37        second_number = ''
38        the_number = 0
39        
40        for i in word_nums:
41            pos: int = line.find(i)
42            while (pos > -1): # keep finding the number until you can't
43                num_list.append(Numbers(word_nums[i], pos))
44                pos = line.find(i, pos+1)
45
46        for i in range(len(line)):
47            if str.isnumeric(line[i]):
48                num_list.append(Numbers(line[i], i))
49        
50        # create a sorted list (lowest to highest) by position in the string
51        sorted_nums = sorted(num_list, key=lambda n: n.position)
52
53        first_number = sorted_nums[0].number# first element
54        second_number = sorted_nums[-1].number # last element
55        the_number = int(first_number + second_number)
56        sum_numbers += the_number
57        num_list.clear()
58
59print(sum_numbers)

Day 2 - Puzzle 1 - PowerShell

 1<#
 2.DESCRIPTION
 3My PowerShell solution to the puzzle https://adventofcode.com/2023/day/2
 4Puzzle 1
 5
 6.PARAMETER FilePath
 7The file path for the input file
 8#>
 9
10[CmdletBinding()]
11param (
12    [Parameter(Mandatory=$false)]
13    [string]$FilePath='.\day2-puzzle-input.txt'
14)
15
16[uint16]$RedCubesReq = 12
17[uint16]$GreenCubesReq = 13
18[uint16]$BlueCubesReq = 14
19[string]$BlockSetSplitCh = ';'
20[string]$BlockSplitCh = ','
21[string]$BeginLineCh = ':'
22$o = New-Object PSObject -Property @{id=0; red=0; blue=0; green=0;}
23[string]$GameMatch = '^Game\W+(?<GameID>\d+)\:'
24[string]$BlockMatch = '^(?<NumBlocks>\d+)\W+(?<BlockColor>red|blue|green)'
25[uint32]$GameSum = 0
26
27foreach ($line in (Get-Content $FilePath)) {
28    if ($line -match $GameMatch) {
29        $o.id = $Matches['GameID']
30    }
31    else {
32        Write-Error "The GameID did not match for line: $($line)"
33    }
34    [string]$line2 = $line.SubString($line.IndexOf($BeginLineCh)+1)
35    [string[]]$BlockSets = $line2.Split($BlockSetSplitCh)
36    $BlockArray = @()
37    foreach ($Draw in $BlockSets) {
38        $o.red = 0
39        $o.green = 0
40        $o.blue = 0
41        [string[]]$Blocks = $Draw.Split($BlockSplitCh)
42        foreach ($Block in $Blocks) {
43            if ($Block.Trim() -match $BlockMatch) {
44                switch ($Matches['BlockColor']) {
45                    'red' {$o.red = [uint16]::Parse($Matches['NumBlocks'])}
46                    'green' {$o.green = [uint16]::Parse($Matches['NumBlocks'])}
47                    'blue' {$o.blue = [uint16]::Parse($Matches['NumBlocks'])}
48                    Default {Write-Error "Invalid block color: $($Matches['BlockColor'])"}
49                }
50            }
51            else {
52                Write-Error "Bad Block Color Match on: $($Block)"
53            }
54        }
55        $BlockArray += $o.PSObject.Copy()
56    }
57    $TooManyBlocks = $BlockArray | Where-Object {
58        $_.red -gt $RedCubesReq -or 
59        $_.blue -gt $BlueCubesReq -or 
60        $_.green -gt $GreenCubesReq}
61    if ($TooManyBlocks) {
62        Write-Information "Skipped GameID: $($o.id)"
63    }
64    else {
65        $GameSum += $o.id
66    }
67}
68
69Write-Output $GameSum

Day 2 - Puzzle 2 - PowerShell

 1<#
 2.DESCRIPTION
 3My PowerShell solution to the puzzle https://adventofcode.com/2023/day/2
 4Puzzle 2
 5
 6.PARAMETER FilePath
 7The file path for the inpute file
 8#>
 9
10[CmdletBinding()]
11param (
12    [Parameter(Mandatory=$false)]
13    [string]$FilePath='.\day2-puzzle-input.txt'
14)
15
16[string]$BlockSetSplitCh = ';'
17[string]$BlockSplitCh = ','
18[string]$BeginLineCh = ':'
19$o = New-Object PSObject -Property @{id=0; red=0; blue=0; green=0;}
20[string]$GameMatch = '^Game\W+(?<GameID>\d+)\:'
21[string]$BlockMatch = '^(?<NumBlocks>\d+)\W+(?<BlockColor>red|blue|green)'
22[uint32]$GameSum = 0
23[uint16]$MinRedBlocks = 0
24[uint16]$MinBlueBlocks = 0
25[uint16]$MinGreenBlocks = 0
26$BlockArray = @()
27foreach ($line in (Get-Content $FilePath)) {
28    if ($line -match $GameMatch) {
29        $o.id = $Matches['GameID']
30    }
31    else {
32        Write-Error "The GameID did not match for line: $($line)"
33    }
34    [string]$line2 = $line.SubString($line.IndexOf($BeginLineCh)+1)
35    [string[]]$BlockSets = $line2.Split($BlockSetSplitCh)
36    $BlockArray.Clear()
37    $MinRedBlocks = 0
38    $MinGreenBlocks = 0
39    $MinBlueBlocks = 0
40    foreach ($Draw in $BlockSets) {
41        $o.red = 0
42        $o.green = 0
43        $o.blue = 0
44        [string[]]$Blocks = $Draw.Split($BlockSplitCh)
45        foreach ($Block in $Blocks) {
46            if ($Block.Trim() -match $BlockMatch) {
47                switch ($Matches['BlockColor']) {
48                    'red' {$o.red = [uint16]::Parse($Matches['NumBlocks'])}
49                    'green' {$o.green = [uint16]::Parse($Matches['NumBlocks'])}
50                    'blue' {$o.blue = [uint16]::Parse($Matches['NumBlocks'])}
51                    Default {Write-Error "Invalid block color: $($Matches['BlockColor'])"}
52                }
53            }
54            else {
55                Write-Error "Bad Block Color Match on: $($Block)"
56            }
57        }
58        $BlockArray += $o.PSObject.Copy()
59    }
60    # Determine minimum blocks (assuming all colors will have at least 1 block)
61    $MinRedBlocks = ($BlockArray | Measure-Object -Property red -Maximum).Maximum
62    $MinGreenBlocks = ($BlockArray | Measure-Object -Property green -Maximum).Maximum
63    $MinBlueBlocks = ($BlockArray | Measure-Object -Property blue -Maximum).Maximum
64
65    # Calculate product of minimum blocks and add it to the sum of Games
66    $GameSum += ($MinRedBlocks * $MinGreenBlocks * $MinBlueBlocks)
67}
68
69Write-Output $GameSum