[英]How to get the nearest Vector to a given target from a list
因此,想象一下我在Java中创建了一个带有两个变量x
和y
的Vector
类:
public class Vector {
private int x;
private int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY(){
return this.y;
}
}
然后,我创建了向量的ArrayList
:
private List<Vector> vecs = new ArrayList<Vector>();
我已经在该列表中创建了:
8,9
10,5
83473834,938849584985
etc ...
现在我想获得与另一个向量最接近的向量。 例:
private List<Vector> vecs = new ArrayList<Vector>();
private Vector vec = new Vector(1,1);
for(Vector vector:vecs) {
//What do i put here??
}
那么我应该在for循环中放入什么以使其从向量列表中选择最近的向量呢?
我将从向Vector
类distanceTo
添加一个方法开始,该方法计算从该向量到另一个向量的距离:
public double distanceTo(Vector vec) {
double dx = x - vec.x; //calculate the diffrence in x-coordinate
double dy = y - vec.y; //calculate the diffrence in y-coordinate
return Math.sqrt(dx*dx + dy*dy); //use the distance formula to find the difference
}
然后,您可以编写以下方法,以将列表中最接近的向量返回给定向量:
public static Vector closest(Vector target, List<Vector> list) {
Vector closest = list.get(0); //this variable will kep track of the closest vector we have found yet. We simply start with the first one
for(int i = 1; i < list.size(); i++) { //loop over the list, skipping the first entry
Vector curr = list.get(i); //get the current vector from the list
if (target.distanceTo(curr) < target.distanceTo(closest)) //if the current vector is closer to target than the closest one yet
closest = curr; //keep the current vector as the new closest one
}
return closest; //return the resulting vector
}
然后可以这样使用该方法:
Vector target = new Vector(1, 2);
List<Vector> vecs = new ArrayList<Vector>();
vecs.add(new Vector(-2, 6));
vecs.add(new Vector(1, 3));
vecs.add(new Vector(4, 0));
vecs.add(new Vector(8, -1));
Vector closest = findClosest(target, vecs);
如您所见,我试图尽我所能来解释代码,但是随时可以提出任何其他问题!
编辑另一种方法是:
public double distanceTo(Vector vec1,Vector vec2) {
double dx = vec2.x - vec1.x; //calculate the diffrence in x-coordinate
double dy = vec.y - vec1.y; //calculate the diffrence in y-coordinate
return Math.sqrt(dx*dx + dy*dy); //use the distance formula to find the difference
}
这是如果您不能将其放入向量类中
这是一个基本的编程问题。 它与OpenGL不相关。 一个简单的线性搜索如下所示:
private List<Vector> vecs = new ArrayList<Vector>();
private Vector vec = new Vector(1,1);
Vector minDistanceVector = null;
int minDistanceSquared = Integer.MAX_VALUE;
for(Vector vector : vecs) {
//Calculate the distance
//This could be a member function of Vector
int dx = vector.getX() - vec.getX();
int dy = vector.getY() - vec.getY();
int squaredDistance = dx * dx + dy * dy;
if(squaredDistance < minDistanceSquared) {
minDistanceSquared = squaredDistance;
minDistanceVector = vector;
}
}
之后,您将在minDistanceVector
拥有最接近的向量。 我选择了欧式距离,因为这可能就是您想要的。 但是,您当然可以使用任何其他距离。
如果您想要更有效的方法,则可能需要在这些点上构建一些加速度数据结构并对其进行查询(例如,网格,kd树,四叉树等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.