fork(3) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static double SegIntersection(double x11, double y11, double x12, double y12,
  11. double x21, double y21, double x22, double y22)
  12. {
  13. double dx1 = x12-x11;
  14. double dy1 = y12-y11;
  15. double dx2 = x22-x21;
  16. double dy2 = y22-y21;
  17. double dxx = x11-x21;
  18. double dyy = y11-y21;
  19. double div, t, s;
  20.  
  21. div = dy2*dx1-dx2*dy1;
  22. if (Math.abs(div) < 1.0e-10) //better to compare abs(div) with small Eps
  23. return 99999.0; //collinear case
  24.  
  25. t = (dx1*dyy-dy1*dxx) / div;
  26. if (t < 0 || t > 1.0)
  27. return 88888.8; //intersection outside the first segment
  28. s = (dx2*dyy-dy2*dxx) / div;
  29. if (s < 0 || s > 1.0)
  30. return 77777.7; //intersection outside the second segment
  31. return x11 + s * dx1;
  32. }
  33.  
  34. public static void main (String[] args) throws java.lang.Exception
  35. {
  36. System.out.println(SegIntersection(0, 0, 1, -1, 2, 1, 1, 2));
  37. System.out.println(SegIntersection(0, 0, 2, 0, 4, -1, 1, 2));
  38. System.out.println(SegIntersection(0, 0, 4, 0, 2, 1, 1, 2));
  39. System.out.println(SegIntersection(0, 0, 4, 0, 4, -1, 1, 2));
  40. }
  41. }
Success #stdin #stdout 0.07s 51492KB
stdin
Standard input is empty
stdout
99999.0
77777.7
88888.8
3.0