N个点中寻找多个最近两点的计算O(N²)
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct point
{
float x;
float y;
}point;
float distance(point a,point b);
float randFloat(void);
int main(void)
{
float d=5;
int cnt=0,N=5;
point *a=malloc(N*(sizeof(*a)));
for(int i=0; i<N; i++)
{
a[i].x=randFloat();
a[i].y=randFloat();
printf("%d %d\n",a[i].x,a[i].y);
}
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
if(distance(a[i], a[j])<d)
cnt++;
printf("%d %f\n",cnt,d);
}
float distance(point a, point b)
{
float dx=a.x-b.x,dy=a.y-b.y;
return sqrt(dx*dx+dy*dy);
}
float randFloat(void)
{
return 1.0*rand()/RAND_MAX;
}
posted on 2018-03-05 17:06 MACHINE_001 阅读(116) 评论(0) 编辑 收藏 举报