All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars    
perplexus dot info

Home > Algorithms
Intersecting lines (Posted on 2003-07-01) Difficulty: 3 of 5
You are given two straight line segments, each defined by the coordinates of its endpoints. Segment AB goes from (Ax,Ay) to (Bx,By) and segment CD - from (Cx,Cy) to (Dx,Dy).

How would you determine if the two line segments intersect?

(Assume that you can't just draw the lines and see)

See The Solution Submitted by levik    
Rating: 4.0000 (2 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
No Code, just theory | Comment 10 of 20 |

I don't have any code or anything, but the basic idea is this:

Using the points given, find the Slope of each line - call them mAB and mCD. You'd need a check to see if |mAB| = |mCD| but that's a trivial case.

Next using the points given, and the all-purpose Line Equation y = m*x + b, find bAB and bCD.

For the moment, treat the two segments as lines and find the X coordinate of the "intersection point". This is easily done by substituting for y and solving for x: x' = (bAB - bCD)/(mCD - mAB)

Next you have to check to see if this intersection point exists on BOTH segments. This is easily done by checking to see if Ax <= x' <= Bx, and Cx <= x' <= Dx (note: those <= signs could be >= signs if Ax>=Bx or Cx>=Dx but you can easily check which cases you are dealing with first)

Using x' solve for y' and repeat the segment-check with Ay, By, Cy and Dy.

At first I thought the x' check was all that was needed, but then I considered a vertical segment and another segment that passes over it such that if you only extended the vertical segment there would be an intersection. In this case x' = Ax = Bx, and would satisfy Cx <= x' <= Dx, so you would come to a false conclusion. That's why you need to check y' too.

If the format of my answer isn't "valid" for the Algorithms section, I apologize and please let me know so I don't do it again.

Later!
  Posted by nikki on 2003-07-02 13:41:53
Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (1)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (16)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information