2015-11-28 27 views
1

我正在试图从数组中获取最近的2个点。查找数组中的2个最近点数

在这里,我只得到cosest。 (i + = 6因为我将位置和颜色保存到数组)但是我怎么能得到最接近的?

nIdx = 0; 
float dst1; 
float dst2 = sqrt(vert[0] - x) + sqrt(vert[1] - y); 
for (int i = 6; i < vert.length; i+=6) { 
    dst1 = sqrt(vert[i] - x) + sqrt(vert[i+1] - y); 
    if (dst2 > dst1) { 
     nIdx = i; 
     dst2 = dst1; 
    } 
} 

我tryed做到这一点:

if (dst2 > dst1) { 
    n2Idx = nIdx; 
    nIdx = i; 
    dst2 = dst1; 
} 

这确实在某些情况下工作。但如果nIdx确实挥舞拳头指数。 n2Idx不会更改为nIdx的最后一个。

那么我认为我somethink错:

float dst1 = sqrt(vert[0] - x) + sqrt(vert[1] - y); 
float dst2 = sqrt(vert[6] - x) + sqrt(vert[7] - y); 
for (int i = 0; i < vert.length; i+=6) { 
    float dst = sqrt(vert[i] - x) + sqrt(vert[i+1] - y); 
    //noinspection StatementWithEmptyBody 
    if (dst >= dst2) { 
    } else if (dst <= dst1) { 
     dst2 = dst1; 
     dst1 = dst; 
    } else { 
     dst2 = dst; 
    } 
} 

回答

1

款待dst1dst2为有序对,即dst1较小并且dst2较大(或两者距离相等)。当你走你的观点的列表,计算候选距离dst,并执行下列操作之一:

  • 如果dst大于或等于dst2,什么也不做
  • 如果dst小于或等于dst1 ,将dst1改为dst2,并将dst改为dst1
  • 否则,将dst改为dst2

在循环dst1的完成和dst2将有两个最小距离:

index ind1 = 0; 
index ind2 = 6; 
float dst1 = sqrt(vert[ind1] - x) + sqrt(vert[ind1+1] - y); 
float dst2 = sqrt(vert[ind2] - x) + sqrt(vert[ind2+1] - y); 
// Make sure dst1 and dst2 are ordered to begin with 
if (dst2 < dst1) { 
    float td = dst1; 
    dst1 = dst2; 
    dst2 = td; 
    ind1 = 6; 
    ind2 = 0; 
} 
// Start loop at 12, because we have processed the first two indexes 
for (int i = 12 ; i < vert.length; i += 6) { 
    float dst = sqrt(vert[i] - x) + sqrt(vert[i+1] - y); 
    if (dst >= dst2) { 
     continue; 
    } 
    if (dst <= dst1) { 
     dst2 = dst1; 
     ind2 = ind1; 
     dst1 = dst; 
     ind1 = i; 
    } else { 
     dst2 = dst; 
     ind2 = i; 
    } 
} 
+0

你的意思是用招什么,我怎么可能让数组的索引。 –

+0

@DarioKowalski“move”与“assign”相同。要获得索引,请将'ind1'和'ind2'与'dst1'和'dst2'一起存储。每当你对'dstX'做些什么时,对'indX'做同样的事情。 – dasblinkenlight

+0

它在某些情况下做了些工作,但有时候都会到索引0。 –

相关问题