MENU

Advent of Code Day 1

Well it’s that time of year again. I’ll inevitably get really into this thing for a few nights, and then around day 5 or 6, full on ragequit after an exhausting 3 AM troubleshooting session.

My overly ambitious plan is to try to mix in a few different languages/technologies.. I’ve heard of people using a different language every day, but that’s 12 days, or like 10 more languages than I could possibly manage.

Anyway, here is day 1 though, in Excel VBA:

Option Explicit

Function GetNewDialPosition(instruction As String, currentDialPosition As Integer) As Integer
    Dim direction As String
    Dim amount As Long
    Dim rawPosition As Integer 'Can be negative
    Dim actualPosition As Integer 'Always between 0 and 99
    
    direction = Left(instruction, 1)
    amount = Int(Right(instruction, Len(instruction) - 1))
    
    If direction = "R" Then
        rawPosition = (currentDialPosition + amount) Mod 100
    Else
        rawPosition = (currentDialPosition - amount) Mod 100
    End If
    If rawPosition < 0 Then
        actualPosition = rawPosition + 100
    Else
        actualPosition = rawPosition
    End If
    GetNewDialPosition = actualPosition
End Function

Function GetPassingZeroes(instruction As String, currentDialPosition As Integer) As Long
    Dim direction As String
    Dim amount As Long
    Dim passingZeroes As Long
    
    direction = Left(instruction, 1)
    amount = Int(Right(instruction, Len(instruction) - 1))
    
    If direction = "R" Then
        passingZeroes = Abs(Int((currentDialPosition + amount) / 100))
        If (currentDialPosition + amount) Mod 100 = 0 Then
            passingZeroes = passingZeroes - 1
        End If
    Else
        passingZeroes = Abs(Int((currentDialPosition - amount) / 100)) - Abs(Int(currentDialPosition / 100))
        If currentDialPosition = 0 Then
            passingZeroes = passingZeroes - 1
        End If
    End If
    GetPassingZeroes = passingZeroes
End Function


Sub GetPassword()
    Dim currentRow As Long
    Dim currentDialPosition As Integer
    Dim currentInstruction As String
    Dim lastRow As Long
    Dim numberOfZeroes As Long
    Dim numberOfZeroesPart2 As Long
    
    currentDialPosition = 50
    numberOfZeroes = 0
    numberOfZeroesPart2 = 0
    lastRow = 4780
    
    For currentRow = 1 To lastRow
        numberOfZeroesPart2 = numberOfZeroesPart2 + GetPassingZeroes(Cells(currentRow, 1).Value, currentDialPosition)
        currentDialPosition = GetNewDialPosition(Cells(currentRow, 1).Value, currentDialPosition)
        If currentDialPosition = 0 Then
            numberOfZeroes = numberOfZeroes + 1
            numberOfZeroesPart2 = numberOfZeroesPart2 + 1
        End If
    Next
    
    MsgBox "The password is: " & CStr(numberOfZeroes) & " for part 1 and " & CStr(numberOfZeroesPart2) & " for part 2"
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *