Advertisement
candyapplecorn

Is It a Right Triangle?

Dec 28th, 2015
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Turned a math practice problem into a program.
  2. // triangles holds an array of arrays of points, each
  3. // of which defines a triangle. The program finds out
  4. // whether or not those are right triangles.
  5. // I decided to write this program because doing it
  6. // by hand was boring and I was bored. Hey, who says
  7. // nodejs has to be just for web apps / servers? Works
  8. // fine for a scripting language too!
  9. var inverse = num => 1 / num;
  10. var slope = (p1, p2) => (p1.y - p2.y) / (p1.x - p2.x);
  11. function right(p1, p2, p3){
  12.     // call node with flag '--harmony-destructuring' to enable this
  13.     var [ s1, s2, s3 ] = [ slope(p1, p2), slope(p1, p3), slope(p2, p3) ];
  14.     return s1 == inverse(s2) || s1 == inverse(s3) || s2 == inverse(s3);
  15. }
  16.  
  17. var triangles = [
  18.     [
  19.         {x:0, y:7},
  20.         {x:-4, y:-2},
  21.         {x:5, y:2}
  22.     ],
  23.     [
  24.         {x:5, y:5},
  25.         {x:5*Math.sqrt(3), y:-5*Math.sqrt(3)},
  26.         {x:-5, y:-5}
  27.     ],
  28.     [
  29.         {x:4, y:5},
  30.         {x:-4, y:-1},
  31.         {x:2, y:-9}
  32.     ],
  33.     [
  34.         {x:8, y:6},
  35.         {x:4, y:4},
  36.         {x:-1, y:10}
  37.     ]
  38. ];
  39.  
  40. console.log(triangles.map(
  41. function(set){
  42.     return "Is a right triangle? " + right(set[0], set[1], set[2]);
  43. }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement