I have unknown number of objects in 3D Space, I would like to know what is the fastest way to detect if two objects or many objects have a distance less than a threshold between each others.
I think that is an n! problem, but I would like a better way for solving it.
I have tried the following pseudo code, and I need your comment about it.
for (int y=0; y<blobList.size();y++){
for (int x =1; x<blobList.size();x++)
{
CvPoint *blob_a = new CvPoint();
CvPoint *blob_b = new CvPoint();
blob_a->x = blobList[x].second->maxx;
blob_a->y = blobList[x].second->maxy;
blob_b->x = blobList[y].second->maxx;
blob_b->y = blobList[y].second->maxy;
double dist = distance(blob_a,blob_b);
cout<< " distance between blob "<<blobList[y].second->label<<"and "<<blobList[x].second->label<<endl;
cout<<dist<<endl;
if( dist<ParamMgr.fDistance)
{
cout<< " Collision between "<<blobList[y].second->label<<"and "<<blobList[x].second->label<<endl;
}
else {
cout<< " "<<endl;
}
}
I can think of three solutions, each with a different time\space tradeoff.
n x n array
If you have a small number n of objects and a distance function D(n1, n2), you can compute the distances in advance.
Create a 2D n X n array. In array[i, j] store the result of D(ni, nj).
Pros:
Cons:
Memoization
Memoize your distance function to remember previous calls.
R-Tree
The standard data structure for storing objects in 2D\3D Objects like Points and Polyhedrons is R-Trees. In short, your objects are grouped into 3D cubes of near-by items. It provides efficient insertion and lookup time of log(n) time, and threshold distance lookup is extremely efficient, especially when the answer is negative.
Quoting the Wikipedia article:
And:
You have R-Tree implementations in most modern programming languages.