I have 2D Points in an arraylist (i.e. A, B, C, D), there can contain an arbitrary number of points that represent a line string strung together.
Assume I had a point X that fell between points B and C, how can I ensure that the output of the function is an arraylist with points "B" and "C" are returned (or simply pointA or pointB are assigned to points "B" and "C") given the following two cases:
1- Point X is closer to B than C, but still falls between B and C
2- Point X is closer to C than B, but still falls between C and B
3- Point X is closer to C than G (maybe because the line segments from the array list is oddly shaped like a U or something), but the function should return either the points C and D or C and B, depending on whichever is the closest to pointX.
My current code is as follows, assume pointX is passed into a function that does the following:
Point pointA = null;
Point pointB = null;
int minDistance = Integer.MAX_VALUE;
for(int i = 0; i < pointlist.size(); i++) {
int distance = pointlist.get(i).getDistanceToPoint(xPoint);
if(distance < minDistance) {
if(pointB != null) {
pointB = pointA;
}
minDistance = distance;
pointA = pointlist.get(i);
} else {
pointB = pointA;
pointA = pointlist.get(i);
}
}
The above meets case #1, but not case #2. What is the best way to do this such that pointA is equal to "B", and pointB is equal to "C"? If there is a better way to do this, I am open to it.
Its just the two points that are closest to pointX right? It is not just a 1st and second closest point, if the arraylist of points happened to form a U shape, or some shape that made it so that two points were closest, but not necessarily adjacent to each other, if the function returned those two points, that is incorrect. It should instead return the first point closest to it, then the 2nd point that is adjacent to that point. UNLESS the user may have specified to start from point "4" or a specific index such that if the 6th point was the 2nd closest point to it, then the result would return that 6th point along with the 5th or the 7th, depending on which line segment it falls within.