fork download
  1. #include <stdio.h>
  2.  
  3. struct point2d { /* 2次元空間の点のx座標とy座標をそれぞれdoubleに格納 */
  4. double x, y;
  5. };
  6.  
  7. struct linesegment { /* 線分の始点sと終点eをそれぞれstruct point2dに格納 */
  8. struct point2d s, e;
  9. };
  10.  
  11. /* 交点判定 (1:交わる、0:交わらない) */
  12. int if_intersect(struct linesegment line1, struct linesegment line2)
  13. {
  14. double m[2]; /* 傾き */
  15. int f_mv[2]; /* y軸と平行かのフラグ */
  16. struct point2d kt; /* 交点 */
  17.  
  18. /* 傾き */
  19. f_mv[0] = (line1.e.x == line1.s.x) ? 1 : 0;
  20. if (f_mv[0] == 0) {
  21. m[0] = (line1.e.y - line1.s.y) / (line1.e.x - line1.s.x);
  22. }
  23. f_mv[1] = (line2.e.x == line2.s.x) ? 1 : 0;
  24. if (f_mv[1] == 0) {
  25. m[1] = (line2.e.y - line2.s.y) / (line2.e.x - line2.s.x);
  26. }
  27. /* 平行か? */
  28. if (f_mv[0] == 1 && f_mv[1] == 1) {
  29. return 0;
  30. }
  31. if (f_mv[0] == 0 && f_mv[1] == 0) {
  32. if (m[0] == m[1]) {
  33. return 0;
  34. }
  35. }
  36. /* 交点計算 */
  37. if (f_mv[0] == 0 && f_mv[1] == 0) {
  38. kt.x = (m[0] * line1.s.x - line1.s.y - m[2] * line2.s.x + line2.s.y) / (m[0] - m[1]);
  39. kt.y = m[0] * kt.x - m[0] * line1.s.x + line1.s.y;
  40. } else if (f_mv[0]) {
  41. kt.x = line1.s.x;
  42. kt.y = m[1] * line1.s.x - m[1] * line2.s.x + line2.s.y;
  43. } else if (f_mv[1]) {
  44. kt.x = line2.s.x;
  45. kt.y = m[0] * line2.s.x - m[0] * line1.s.x + line1.s.y;
  46. }
  47. /* 交点が線分の範囲内か判定 */
  48. if (f_mv[0]) {
  49. if (line1.s.y < line1.e.y) {
  50. if (line1.s.y <= kt.y && kt.y <= line1.e.y) {
  51. return 1;
  52. }
  53. } else {
  54. if (line1.e.y <= kt.y && kt.y <= line1.s.y) {
  55. return 1;
  56. }
  57. }
  58. }
  59. if (f_mv[1]) {
  60. if (line2.s.y < line2.e.y) {
  61. if (line2.s.y <= kt.y && kt.y <= line2.e.y) {
  62. return 1;
  63. }
  64. } else {
  65. if (line2.e.y <= kt.y && kt.y <= line2.s.y) {
  66. return 1;
  67. }
  68. }
  69. }
  70. return 0;
  71. }
  72.  
  73. /* main */
  74. int main()
  75. {
  76. struct linesegment line1 = {
  77. {0.0, 0.0},
  78. {2.0, 1.0}
  79. };
  80. struct linesegment line2 = {
  81. {1.0, 2.0},
  82. {1.0, 0.6}
  83. };
  84.  
  85. "線分 [%f, %f]-[%f, %f]\n"
  86. "と [%f, %f]-[%f, %f]\n"
  87. "は、交わ%s\n"
  88. , line1.s, line1.e, line2.s, line2.e
  89. , if_intersect(line1, line2) ? "る" : "らない"
  90. );
  91. return 0;
  92. }
  93.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
線分 [0.000000, 0.000000]-[2.000000, 1.000000]
と   [1.000000, 2.000000]-[1.000000, 0.600000]
は、交わらない