After the part 1 of the tutorial, part 2 is born to kill.
I have one small tweak for the naive method, in theory, it will can only speed up the detection. so if your segments are always in extreme condition and keep running to the worst case for the previous algorithm, with this one you can't lose much.
Sort set B and compare with set A, but this time, If a x1 for one segment in set B is larger than the x2 in a set A segment, break the loop because all the x1's after that segment will have larger x1 values.
Just change following part in the original code:
for(i=0;i<size;++i){
for(n=0;n<size;++n){
if(b[n].x1<=a[i].x2 && a[i].x1<=b[n].x2)
{
++counter;
}
}
}
to
for(i=0;i<size;++i){
for(n=0;n<size;++n){
if(b[n].x1<=a[i].x2)
{
if(a[i].x1<=b[n].x2){
++counter;
}
}else{
break;
}
}
}
This code is usually good enough for most detections you will ever use if you use it to create a game(unless you have 20000 3D objects flying around).
To extend the 1D segment detection to 2D axis aligned bounding rectangle detection. Create a pair of y coordinates and x coordinates for each rectangle. Do the x's and y's separately. When both 1D segments for x and 1D segments for y need intersects, those 2D rectangles intersects. Same for 3D boxes, just add the z coordinates.
When come to databases, advanced algorithms comes to play.
Currently, all the fastest algorithms in this field works with tree structures. I believes the best thing for the 1D problem is the interval tree, a data structure mentioned in both Introduction to Algorithms and Computational Geometry. While segment tree costs O(nlog(n)) memory, interval tree cost O(n) memory and just as fast.
Quadtree and Octree proven useful in 2D and 3D respectively.
For hardcore n Dimension hyperrectangles intersection detection, try PR-tree, a R-tree variant.
Recent comments
5 hours 20 min ago
23 hours 2 min ago
1 day 8 hours ago
2 days 17 hours ago
3 days 21 hours ago
4 days 1 hour ago
4 days 1 hour ago
4 days 1 hour ago
4 days 17 hours ago
4 days 18 hours ago