canMakeTriangle

with Carmen Salas • 2024/11/14

Solution

/*
**Problem**
Look at three values at a time. Check if they can form a triangle (given the rules).
Resulting array is naturally arr.length-2.

**Examples/Edge Cases:** 
[1,2,3] => [0]
[1,1000,1000] => [1]

**Data Structures**
- arrays
- conditionals
- loops

**Algorithm** 
Loop through up to third to last index of array
  - for every index, look ahead up to 2 indices
    and check if forming a triangle is possible
  - if yes, store 0 in result arr, otherwise 1
Return result arr

*/

function solution(arr) {
  /* GUARD CLAUSES */
  // initialize res to be false (0) for all trios
  const res = Array(arr.length-2).fill(0);
  for (let i = 0; i < arr.length-2; i++) {
    // guard clauses
    if (arr[i] + arr[i+1] <= arr[i+2]) continue;
    if (arr[i+1] + arr[i+2] <= arr[i]) continue;
    if (arr[i] + arr[i+2] <= arr[i+1]) continue;
    // if it makes through all, trio can make triangle!
    res[i] = 1;
  }
  
  return res;
  
  /* MOON GLYPHS */
  const res = [];
  for (let i = 0; i < arr.length-2; i++) {
    // moon glyphs
    (arr[i] + arr[i+1] <= arr[i+2])
      ? res[i] = 0
      : (arr[i+1] + arr[i+2] <= arr[i])
          ? res[i] = 0
          : (arr[i] + arr[i+2] <= arr[i+1])
              ? res[i] = 0
              : res[i] = 1
  }
  return res;
}

Last updated