gbox
gbox

Reputation: 829

Finding all intersection points in a group of line segments?

I have an array of objects (Lines) and a binary operation (intersection) that returns true/false. The brute force is to duplicate the array an run on a nested for loop.

for (Line line : linesArray) {
            for (int j = 0; j < linesArray.length; j++) {
                if (line.isIntersecting(linesArray[j])) {
                    Point intersection = line.intersectionWith(linesArray[j]);
                    d.drawCircle(intersection.getXInt(), intersection.getYInt(), 3);
                    d.fillCircle(intersection.getXInt(), intersection.getYInt(), 3);
                }
            }
        }

But, there order does not matter, so I thought about generating a subsets of size 2 and check for each subset, but complex wise it does not seems to be any better

Is there an efficient (run time) to do so?

Upvotes: 0

Views: 919

Answers (1)

templatetypedef
templatetypedef

Reputation: 372664

You are correct that enumerating all subsets of size two and checking each will not be an improvement over your existing algorithm. In fact, that's essentially just a restatement of what your algorithm does.

There are faster algorithms for solving the problem of finding all intersections in a collection of line segments. The most famous of these is the Bentley-Ottmann algorithm, which works by sorting the line segments by their x coordinates and sweeping a line over the points from left to right. It works in time O((n + k)log n), where n is the number of line segments and k is the number of intersections.

Other, more modern algorithms exist for solving this problem even faster, but this would likely make for a good starting point.

Hope this helps!

Upvotes: 2

Related Questions