DEV Community

Cover image for Squares With Three Sides
Robert Mion
Robert Mion

Posted on

Squares With Three Sides

Advent of Code 2016 Day 3

Part 1

Three sums and three comparisons

I need to determine which three-sided shapes are valid triangles.

The proof for a valid triangle, per the instructions:

the sum of any two sides must be larger than the remaining side

This seems like the best - perhaps only? - approach:

 |\
 | \  
 |  \
A|   \ B
 |    \
 |_____\
    C

A + B > C?
A + C > B?
B + C > A?
Enter fullscreen mode Exit fullscreen mode

My algorithm in JavaScript:

input.reduce((valids, triangle) => {
  let [A,B,C] = [...triangle.matchAll(/\d+/g)].map(el => +el[0])
  return valids += (
    A + B > C && 
    A + C > B &&
    B + C > A
  ) ? 1 : 0
}, 0)
Enter fullscreen mode Exit fullscreen mode

It generated the correct answer for Part 1!

Part 2

Columns instead of rows

A fun twist that will require nested for loops instead of a single reduce().

My algorithm as pseudocode:

Extract the digits from each line
  Generate a 3-element array in place of the string

Set valid count as 0

For each 3-element array except the last two, skipping two each time
  For each element in the array
    Generate a 3-element array containing the numbers in the same position as the element in the array...from the current and next two arrays
    Increment valid count by 1 only if each pair of side lengths is greater than the non-included side

Return valid count
Enter fullscreen mode Exit fullscreen mode

My algorithm in JavaScript:

let sides = input.map(
  line => [...line.matchAll(/\d+/g)].map(el => +el[0])
)
let valids = 0
for (let row = 0; row < sides.length - 2; row += 3) {
  for (let col = 0; col < 3; col++) {
    let [A,B,C] = sides.slice(row, row + 3).map(el => el[col])
    valids += (
      A + B > C && 
      A + C > B &&
      B + C > A
    ) ? 1 : 0
  }
}
return valids
Enter fullscreen mode Exit fullscreen mode

It generated the correct answer for Part 2!

I did it!!

  • I solved both parts!
  • I leveraged my growing familiarity with regex, reduce() and several array manipulation techniques!
  • With the exception of Day 11, I continue a 2-star streak since Day 22!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay