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!

Top comments (0)