I am confused by an algorithm for counting the number of pairs of N random points which has a distance closer than d = sqrt((p1.x-p2.x)^2 + (p1.y-p2.y)^2)
The general approach is straightforward:
struct point p[N] = .......
for(i = 0; i < N; i++)
for(j = i+1; j < N; j++)
if(distance(p[i], p[j]) < d) cnt++;
Running time is O(N^2).
The improved algorithm is as follows, which is based on 2-dimensional array of lists
typedef struct node *link;
struct node {struct point p; link next};
link **grid; int G; float d; int cnt = 0;
gridinsert(float x, float y)
{
int i, j;
link s;
int X = x * G + 1;
int Y = y * G + 1;
link t = malloc(sizeof(link));
t->p.x = x; t->p.y = y;
for(i = X - 1; i <= X + 1; i++)
for(i = Y - 1; j <= Y + 1; j++)
for(s = grid[i][j]; s != NULL; s = s->next)
if(distance(s->p, t->p) < d) cnt++;
t->next = grid[X][Y];
grid[X][Y] = t;
}
float randFloat() {return 1.0*rand()/RAND_MAX};
void main()
{
int i, j, N = atoi(argv[1]);
d = atof(argv[2]); G = 1/d;
grid = malloc2d(G+2, G+2); //malloc2d is a function to allocate memory for 2D array
for(i = 0; i < G+2; i++)
for(j = 0; < G+2; j++)
grid[i][j] = NULL;
for(i = 0; i < N; i++)
gridinsert(randFloat(), randFloat());
printf("%d\n", cnt);
}
How to understand this algorithm and what is the running time now?