Advent of Code: Day 3 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 3, part 1

Simplified problem: You are given a design document with specifications for triangles:

Each line represents the lengths of three sides of a triangle.

Given the rule that a valid triangle is a triangle where the sum of any two sides is greater than the length of the remaining side, how many of these triangles are valid?

Solution

Create a Triangle object:

  • Lengths=List of 3 lengths
  • LongestLength=Maximum(Lengths)
  • SumOfRemainingSides=(the sum of the remaining 2 lengths in Lengths)
  • IsValidTriangle=SumOfRemainingSides > LongestLength
  1. Set Triangles=new List of Triangle
  2. Set input=(input)
  3. For each line in input
    1. Split line using the space character as the separator, to get lengths=(an array of 3 numbers)
    2. Set triangle=new Triangle(Lengths=lengths)
    3. Add triangle to Triangles
  4. End For
  5. Return number of triangles in Triangles where IsValidTriangle=true

Day 3, part 2

Using the same input, the specifications for each triangle is listed in columns, not rows. Given the input above, this would create 6 triangles, each containing lengths in the same hundreds (101,102,103 etc).

Solution

  1. Set Triangles=new List of Triangle
  2. Set input=(input)
  3. Set triangleLengths=(array containing 3 numbers)
  4. Set LengthSide=0
  5. For i=1 to 3 (loop through columns)
    1. For each line in input
      1. Split line using the space character as the separator, to get lengths=(an array of 3 numbers)
      2. Set triangleLengths[0]=lengths[i] (i=1 to 3, 1st to 3rd column)
      3. Set lengthSide = lengthSide+1
      4. If lengthSide=3 (triangleLengths now has three sides – add triangle and reset for next triangle)
        1. Set lengthSide=0
        2. Set triangle=new Triangle(Lengths=triangleLengths)
        3. Add triangle to Triangles
      5. End If
    2. End For
  6. End For
  7. Return number of triangles in Triangles where IsValidTriangle=true

You can find the full solution on Github

Leave a Reply

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