So this question already has many answers but i was not able to find one for my specific problem. I have a very special case with only positive integers where always a line has always either the same x-values or the same y-values. I have two such lines and now only have to know if there are intersecting, not where. I know I could use any normal algorithm, but I believe that would be completely overdoing it. If not tell me. The code I already has is my third try and it is a complete mess and I don't think it has the right approaches.
Asked
Active
Viewed 601 times
-2
-
1please show your code – Turo Dec 24 '17 at 10:41
-
What does 'positive integers where always a line has always either the same x-values or the same y-value' mean? Are your lines always vertical, or are they always horizontal? – elsyr Dec 24 '17 at 10:43
-
@elsyr This can change. But they are always parallel to the x or y axis. – MegaIng Dec 24 '17 at 10:44
-
How are your lines structured? Are they created via equation, or do you have a set of points? – elsyr Dec 24 '17 at 10:46
-
@elsyr They have start and end points, so I have to check for them as well, and I'm not sure how to do that. – MegaIng Dec 24 '17 at 10:47
1 Answers
2
You have two lines, determined by start and end points.
{ (x1,y1), (x2,y2) }, { (x3,y3), (x4,y4) }
make a function to see if two ranges overlap.
function rangeOverlaps(a1, a2, b1, b2) {
let x1 = Math.min(a1, a2),
x2 = Math.max(a1, a2),
y1 = Math.min(b1, b2),
y2 = Math.min(b1, b2);
return x1 <= y2 && y1 <= x2;
}
And a function to see if both the x and y ranges overlap.
function linesIntersect(x1, x2, x3, x4, y1, y2, y3, y4) {
return (rangeOverlaps(x1, x2, x3, x4) && rangeOverlaps(y1, y2, y3, y4));
}
function rangeOverlaps(a1, a2, b1, b2) {
let x1 = Math.min(a1, a2),
x2 = Math.max(a1, a2),
y1 = Math.min(b1, b2),
y2 = Math.min(b1, b2);
return x1 <= y2 && y1 <= x2;
}
function linesIntersect(x1, x2, x3, x4, y1, y2, y3, y4) {
return (rangeOverlaps(x1, x2, x3, x4) && rangeOverlaps(y1, y2, y3, y4));
}
let x1 = 0,
y1 = 2,
x2 = 2,
y2 = 2,
x3 = 0,
y3 = 2,
x4 = 1,
y4 = 2;
let intersects = linesIntersect(x1, x2, x3, x4, y1, y2, y3, y4);
console.log(intersects);

JasonB
- 6,243
- 2
- 17
- 27
-
Good answer but it seems not to handle the case if one line is inside another. `{(0,2),(2,2)},{(0,2),(1,2)}` returns false, even if it should return true. I would add to extra cases but I believe therw is a better way. Could you show it? – MegaIng Dec 24 '17 at 12:42
-
^ I've fixed the rangeOverlaps function. If you know your data is always well formed with x1 <= x2 etc. you could shorten the rangeOverlaps function a bit. – JasonB Dec 24 '17 at 15:54
-
Very good, almost perfect. One last thing: {(1,0),(1,2)},{(0,2),(2,2)} should intersect, {(1,0),(1,2)},{(0,2),(1,2)} should not. Is this possible? currently they both return no intersection. – MegaIng Dec 24 '17 at 16:15