我正在尝试将2个最近的点从数组中移到另一个点。
在这里,我只会感到胆小。(i + = 6,因为我将POSITION和COLOR保存到数组中)但是,如何才能使2.最接近?
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;
}
}
我试图做到这一点:
if (dst2 > dst1) {
n2Idx = nIdx;
nIdx = i;
dst2 = dst1;
}
在某些情况下,这确实可行。但是如果nIdx
不进行拳头索引。n2Idx
不会更改为的最后一个nIdx
。
好吧,我想我做错了:
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;
}
}
将dst1
和dst2
视作有序对,即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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句