gpt4 book ai didi

java - 如何从列表中获取最接近给定目标的 vector

转载 作者:行者123 更新时间:2023-11-30 06:50:54 24 4
gpt4 key购买 nike

假设我在 Java 中创建了一个带有两个变量 xyVector 类:

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 vector :

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 ?

最佳答案

我将从向 VectordistanceTo 添加一个方法开始,该方法计算从该 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com