如何找到最近的 CGPoint 并从 NSArray 中创建一个集群?

How to Find the nearest CGPoint and make a cluster from NSArray?

我有一个场景,就是在 UIView 中为最近的 CGPoint 聚类。所以我有一组 CGPoint NSArray,我试图获得最接近的值并进行聚类,但我无法获得逻辑: // 我的代码

  for (CGPoint firstObjOfCGPoint in cgPointGroupArray) {            

    for (CGPoint nextPoint in cgPointGroupArray) {

     if (30>[self distanceBetween: firstObjOfCGPoint and:nextPoint]){                
                [shortestClusterArr addObject:nextPoint];
            }
            else{
                [longestClusterArr addObject:nextPoint];
            }
        }
           if(shortestClusterArr.count>2){
             //clustered marker
               [self addClusterMarker:shortestClusterArr];
           }
           else{
              //dont cluster marker 
           }
    }
}


    //find distance

    - (float)distanceBetween:(CGPoint)p1 and:(CGPoint)p2
    {
        return hypotf((p1.x-p2.x), (p1.y-p2.y));

    } 

以上代码,循环时间获取重复点以及覆盖同一对象,所以如果有人知道这里的逻辑注释,..

您需要在添加之前检查对象是否已经存在。像这样:

for (CGPoint nextPoint in cgPointGroupArray) {
            if (30>[self distanceBetween:point and: nextPoint]) {
                if (![shortestClusterArr containsObject:nextPoint])
                  [shortestClusterArr addObject:nextPoint];
            }
            else{
                if (![longestClusterArr containsObject:nextPoint])
                  [longestClusterArr addObject:nextPoint];
            }
        }