Advent of Code 2021 – Day 2

Advent of Code 2021 – Day 2

Well we’re back for day 2 of Advent of Code 2021. If you haven’t checked out day 1 yet, you can do so here. You may remember yesterday Santa got in to his trusted submarine and decided to go hunting for his sleigh keys; that an elf had accidently knocked over the side of the boat.

Day two isn’t much different, but our movement within the submarine has changed. We now have to take into account our Horizontal and Vertical position.

In the second part we’re not only looking at the horizontal or vertical position, we’re also looking at an aim in that direction.

Lets first have a look at the sample input to see the type of data we’re working with.

forward 5
down 5
forward 8
up 3
down 8
forward 2

We use the up and down for the vertical position, and forward for the horizontal making it quite easy to find each position. The final step is to times the horizontal and vertical position.

In this solution below lets look at some of the steps I took

$input = Get-Content ("input.txt")

#Part 1
$Hor, $Ver = 0

$input | ForEach-Object { 
    $Direction = $($_ -split " ")[0]
    [int]$Count = $($_ -split " ")[1]

    switch ($Direction) { 
        "Up" { $Ver = $Ver - $Count }
        "Down" { $Ver = $Ver + $Count }
        "Forward"  { $Hor = $Hor + $Count }
    }
    
}

Write-Host "Final Position: $($Hor * $Ver)"

I get the direction and the number quite easily by splitting on the space within the input line. Remembering to set the number as an int.

Then just using a simple switch statement to amend the horizonal and vertical count.

Part two is when it got a little more interesting, this time taking into account the aim, I am sure this could have been done a lot easier but below was what I came up with.

Taking a lot of what I had already implemented into part 1.

Part2:

$input = Get-Content ("input.txt")

$Hor, $Ver, $Aim = 0

$input | ForEach-Object { 
    $Direction = $($_ -split " ")[0]
    [int]$Count = $($_ -split " ")[1]

    switch ($Direction) { 
        "Up" { 
            $Ver = $Ver - $Count
            $LastDirection = $Ver 
        }
        "Down" { 
            $Ver = $Ver + $Count
            $LastDirection = $Ver
        }
        "Forward"  { 
            $Hor = $Hor + $Count
            $Aim = $Aim + $count * $LastDirection
        }
    }
}

Write-Host "Final Position: $($Hor * $Aim)"

Well how did you do, did you find interesting ways to solve this solution let me know in the comments.

Leave a Reply

Your email address will not be published.