lines-intersection.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.intersection = void 0;
  4. var tslib_1 = require("tslib");
  5. function inside(x1, x2, y1, y2, xk, yk) {
  6. return ((x1 === x2 || (Math.min(x1, x2) <= xk && xk <= Math.max(x1, x2))) &&
  7. (y1 === y2 || (Math.min(y1, y2) <= yk && yk <= Math.max(y1, y2))));
  8. }
  9. function update(ans, x, y) {
  10. var out = ans;
  11. if (!ans.length || x < ans[0] || (x === ans[0] && y < ans[1])) {
  12. out[0] = x;
  13. out[1] = y;
  14. }
  15. }
  16. /**
  17. * 求两个线段的交点坐标
  18. * 参考:https://leetcode-cn.com/problems/intersection-lcci/solution/jiao-dian-by-leetcode-solution/
  19. */
  20. function intersection(_a, _b, _c, _d) {
  21. var _e = tslib_1.__read(_a, 2), x1 = _e[0], y1 = _e[1];
  22. var _f = tslib_1.__read(_b, 2), x2 = _f[0], y2 = _f[1];
  23. var _g = tslib_1.__read(_c, 2), x3 = _g[0], y3 = _g[1];
  24. var _h = tslib_1.__read(_d, 2), x4 = _h[0], y4 = _h[1];
  25. var ans = [];
  26. // 若两直线平行
  27. if ((y4 - y3) * (x2 - x1) === (y2 - y1) * (x4 - x3)) {
  28. // 若两线段有重合
  29. if ((y2 - y1) * (x3 - x1) === (y3 - y1) * (x2 - x1)) {
  30. // 分别判断四个点
  31. if (inside(x1, x2, y1, y2, x3, y3)) {
  32. update(ans, x3, y3);
  33. }
  34. if (inside(x1, x2, y1, y2, x4, y4)) {
  35. update(ans, x4, y4);
  36. }
  37. if (inside(x3, x4, y3, y4, x1, y1)) {
  38. update(ans, x1, y1);
  39. }
  40. if (inside(x3, x4, y3, y4, x2, y2)) {
  41. update(ans, x2, y2);
  42. }
  43. }
  44. }
  45. else {
  46. // 联立方程得到 t1 和 t2 的值
  47. var t1 = (x3 * (y4 - y3) + y1 * (x4 - x3) - y3 * (x4 - x3) - x1 * (y4 - y3)) /
  48. ((x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1));
  49. var t2 = (x1 * (y2 - y1) + y3 * (x2 - x1) - y1 * (x2 - x1) - x3 * (y2 - y1)) /
  50. ((x4 - x3) * (y2 - y1) - (x2 - x1) * (y4 - y3));
  51. // 判断 t1 和 t2 是否均在 [0, 1] 之间
  52. if (t1 >= 0.0 && t1 <= 1.0 && t2 >= 0.0 && t2 <= 1.0) {
  53. ans[0] = x1 + t1 * (x2 - x1);
  54. ans[1] = y1 + t1 * (y2 - y1);
  55. }
  56. }
  57. return ans;
  58. }
  59. exports.intersection = intersection;
  60. //# sourceMappingURL=lines-intersection.js.map