Caspermartijn - 1 month ago 23

Java Question

So imagine I've created a

`Vector`

`x`

`y`

`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;

}

}

Then I've craeted an

`ArrayList`

`private List<Vector> vecs = new ArrayList<Vector>();`

I've created in that list:

`8,9`

10,5

83473834,938849584985

etc ...

Now I want to get the closest vector to another vector.

Example:

`private List<Vector> vecs = new ArrayList<Vector>();`

private Vector vec = new Vector(1,1);

for(Vector vector:vecs) {

//What do i put here??

}

So what do i put in the for loop to make it select the nearest vector from the vector list?

Answer

I would start by adding a method to the `Vector`

class, `distanceTo`

, that calculates the distance from this vector to another one:

```
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
}
```

And then you can write the following method that returns the closest vector in a list to a given 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
}
```

This method can then be used like this:

```
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);
```

As youn can see I tried to explain the code as best as I could, but feel free to ask any further questions!