@Test public void testNearestPointInList() { Random rnd = new Random(239827); for (int times = 0; times < 1e5; ++times) { List<IVector2> c = new ArrayList<>(); for (int i = rnd.nextInt(50) + 1; i > 0; --i) { double length = rnd.nextDouble() * 1000; IVector2 vector = Vector2.fromAngle(rnd.nextDouble() * AngleMath.PI_TWO).scaleToNew(length); c.add(vector); } final IVector2 expected = Collections.min(c, new VectorLengthComparator()); final IVector2 result = VectorMath.nearestTo(Vector2f.ZERO_VECTOR, c); assertTrue(result.isCloseTo(expected, 1e-6)); } }
static IVector2 nearestTo(final IVector2 p, final Collection<IVector2> points) { Validate.notEmpty(points); IVector2 closest = null; double closestDist = Double.MAX_VALUE; for (IVector2 vec : points) { double dist = distancePPSqr(vec, p); if (closestDist > dist) { closestDist = dist; closest = vec; } } Validate.notNull(closest); return closest; }
VectorMath { static IVector2 nearestTo(final IVector2 p, final Collection<IVector2> points) { Validate.notEmpty(points); IVector2 closest = null; double closestDist = Double.MAX_VALUE; for (IVector2 vec : points) { double dist = distancePPSqr(vec, p); if (closestDist > dist) { closestDist = dist; closest = vec; } } Validate.notNull(closest); return closest; } }
VectorMath { static IVector2 nearestTo(final IVector2 p, final Collection<IVector2> points) { Validate.notEmpty(points); IVector2 closest = null; double closestDist = Double.MAX_VALUE; for (IVector2 vec : points) { double dist = distancePPSqr(vec, p); if (closestDist > dist) { closestDist = dist; closest = vec; } } Validate.notNull(closest); return closest; } @SuppressWarnings("unused") private  VectorMath(); }
VectorMath { static IVector2 nearestTo(final IVector2 p, final Collection<IVector2> points) { Validate.notEmpty(points); IVector2 closest = null; double closestDist = Double.MAX_VALUE; for (IVector2 vec : points) { double dist = distancePPSqr(vec, p); if (closestDist > dist) { closestDist = dist; closest = vec; } } Validate.notNull(closest); return closest; } @SuppressWarnings("unused") private  VectorMath(); static double distancePP(final IVector2 a, final IVector2 b); static double distancePPSqr(final IVector2 a, final IVector2 b); }
VectorMath { static IVector2 nearestTo(final IVector2 p, final Collection<IVector2> points) { Validate.notEmpty(points); IVector2 closest = null; double closestDist = Double.MAX_VALUE; for (IVector2 vec : points) { double dist = distancePPSqr(vec, p); if (closestDist > dist) { closestDist = dist; closest = vec; } } Validate.notNull(closest); return closest; } @SuppressWarnings("unused") private  VectorMath(); static double distancePP(final IVector2 a, final IVector2 b); static double distancePPSqr(final IVector2 a, final IVector2 b);  }