# intersection between line segments - narrowed precondition

I believe that the issue may already have been discussed here. I want to find if two line segments does intersect and if they do then find and store and intesection points. Now it is already confirmed that one of the line segments will always be parallel to x-axis or y-axis. So in that case how should we reformulate the basic algorithm that checks the line segments intersection?

• Is it known which line segment is axis parallel and which axis it is parallel to? Are you given two line segments, where one of them is parallel to one of the axes but you don't know which line segment or which axis, or are you given the first line segment, knowing it is always parallel to the x axis, and the second one may be any arbitrary line segment? Commented Mar 5, 2016 at 18:04
• These seemingly subtle differences may make a large difference to the approach, and so answerers will need to know which is the case. Commented Mar 5, 2016 at 18:05
• It is confirmed that one of the line segment is either parallel to x-axis or y-axis and the other line segment may be or may be not parallel to either of the axis. Commented Mar 5, 2016 at 18:28

## 2 Answers

The arbitrary line can be expressed as y = a*x+b (assuming it's not parallel to the y axis).

If the other line is parallel to the y axis then you can simply fill in the x coordinate of any point on the line into the formula of the first line. Then you can check whether they intersect by ensuring the result lies between the endpoints of the second line.

For the second line parallel to the x axis you just flip the x and y coordinates.

the arbitrary line can be represented as $P = (x,y) = P_0 + \lambda. \vec{dir}$ (works in n dimensions, no special case). If your other line is $x=x_1$ simply inject this in to solve for $\lambda$ and get $y$: $y=y_0+(x_1-x_0).\frac{{dir}_y}{{dir}_x}$.

• But the other line x = x1 is an infinite line parallel to the y-axis. Is not there a significant difference between a line and a line segment where both are parallel to y-axis ? Commented Mar 4, 2016 at 21:55
• woops, you want segments. then verify that y match, and that $\lambda$ match. Commented Mar 5, 2016 at 0:47