假设我在 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;
}
}
然后我创建了一个 vector ArrayList
:
private List<Vector> vecs = new ArrayList<Vector>();
我在该列表中创建了:
8,9
10,5
83473834,938849584985
etc ...
现在我想获得与另一个 vector 最接近的 vector 。 示例:
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 列表中选择最近的 vector ?
最佳答案
我首先向 Vector
类添加一个方法 distanceTo
,用于计算从该 vector 到另一个 vector 的距离:
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
}
然后您可以编写以下方法,返回列表中与给定 vector 最接近的 vector :
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
}
这是如果你不能把它放入 vector 类
关于java - 如何从列表中获取距离给定目标最近的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813167/