Advent of Code: Day 1 Solution

This year, I’m posting my solutions to the puzzles in the Advent of Code. Each post will consist of pseudocode, with a link to the actual code I used to solve the puzzle on Github.

And now, on with the solution:

Day 1, part 1

Simplified problem: Following a set of instructions in the format x0 where x is a direction (L or R) and 0 is the number of blocks to move, how far away from your start point are you when you arrive at your destination?

  • You always start at block 0,0 and face North.

Solution

  1. Read all instructions and process into correct format
  2. Set PositionX=0
  3. Set PositionY=0
  4. For each instruction, turn in the specified direction and travel the required number of blocks:
    1. If travelling North, increase PositionY by blocks
    2. If travelling East, increase PositionX by blocks
    3. If travelling South, descrease PositionY by blocks
    4. If travelling West, decrease PositionX by blocks
  5. Return the sum of the Absolute Value of both PositionX and PositionY. (X and Y coordinates can be negative values. sing the absolute values will return the positive value of these number).

Day 1, part 2

Using the same instructions, what is the first point at which you cross your path?

Solution

  1. Read all instructions and process into correct format
  2. Set PositionX=0
  3. Set PositionY=0
  4. Set ListOfCoordinates=new List(of Coordinates)
  5. Set FirstPointCrossed=nothing
  6. For each instruction, turn in the specified direction and travel the required number of blocks:
    1. Set i=0
    2. While i<blocks
      1. If travelling North, increase PositionY by 1
      2. If travelling East, increase PositionX by 1
      3. If travelling South, descrease PositionY by 1
      4. If travelling West, decrease PositionX by 1
      5. Set CurrentCoordinates=PositionX,PositionY
      6. If ListOfCoordinates contains the CurrentCoordinates and FirstPointCrossed=nothing
        1. Set FirstPointCrossed=CurrentCoordinates
      7. End if
      8. Add current coordinates (PositionX, PositionY) to ListOfCoordinates
      9. Add 1 to i
    3. End While
  7. Return the value of FirstPointCrossed

Note: the code above will continue to travel the full path, even after we find the first point crossed. After setting FirstPointCrossed, we should exit the While loop and return the value.

 

You can find the full solution on GitHub

Leave a Reply

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