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[1] * 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. if (f_mv[0] == 0 && f_mv[1] == 0) {
  71. if (line1.s.x < line1.e.x) {
  72. if (line1.s.x <= kt.x && kt.x <= line1.e.x) {
  73. return 1;
  74. }
  75. } else {
  76. if (line1.e.x <= kt.x && kt.x <= line1.s.x) {
  77. return 1;
  78. }
  79. }
  80. }
  81. return 0;
  82. }
  83.  
  84. /* main */
  85. int main()
  86. {
  87. struct linesegment line1 = {
  88. {0.0, 0.0},
  89. {2.0, 1.0}
  90. };
  91. struct linesegment line2 = {
  92. {1.0, 2.0},
  93. {1.5, 0.0}
  94. };
  95.  
  96. "線分 [%f, %f]-[%f, %f]\n"
  97. "と [%f, %f]-[%f, %f]\n"
  98. "は、交わ%s\n"
  99. , line1.s, line1.e, line2.s, line2.e
  100. , if_intersect(line1, line2) ? "る" : "らない"
  101. );
  102. return 0;
  103. }
  104.  
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
線分 [0.000000, 0.000000]-[2.000000, 1.000000]
と   [1.000000, 2.000000]-[1.500000, 0.000000]
は、交わる