All right triangles with specified perimeter in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number that specifies the perimeter for a triangle. Our function should return an array of all the triangle side triplets whose perimeter is same as specified by the input.

Example

Following is the code −

 Live Demo

const perimeter = 120;
const findAllRight = (perimeter = 1) => {
   const res = [];
   for(let a = 1; a <= perimeter; a++){
      for(let b = a; b <= perimeter - a; b++){
         for(let c = a; c <= a + b; c++){
            if(a + b + c !== perimeter){
               continue;
            };
            if((a * 2) + (b * 2) === (c * 2)){
               res.push([a, b, c]);
            };
         };
      };
   };
   return res;
};
console.log(findAllRight(perimeter));

Output

Following is the console output −

[ [ 1, 59, 60 ],
   [ 2, 58, 60 ],
   [ 3, 57, 60 ],
   [ 4, 56, 60 ],
   [ 5, 55, 60 ],
   [ 6, 54, 60 ],
   [ 7, 53, 60 ],
   [ 8, 52, 60 ],
   [ 9, 51, 60 ],
   [ 10, 50, 60 ],
   [ 11, 49, 60 ],
   [ 12, 48, 60 ],
   [ 13, 47, 60 ],
   [ 14, 46, 60 ],
   [ 15, 45, 60 ],
   [ 16, 44, 60 ],
   [ 17, 43, 60 ],
   [ 18, 42, 60 ],
   [ 19, 41, 60 ],
   [ 20, 40, 60 ],
   [ 21, 39, 60 ],
   [ 22, 38, 60 ],
   [ 23, 37, 60 ],
   [ 24, 36, 60 ],
   [ 25, 35, 60 ],
   [ 26, 34, 60 ],
   [ 27, 33, 60 ],
   [ 28, 32, 60 ],
   [ 29, 31, 60 ],
   [ 30, 30, 60 ] 
]
raja
Published on 20-Apr-2021 07:55:30
Advertisements