Skip to content

Instantly share code, notes, and snippets.

@akwodkiewicz
Created May 26, 2017 21:11
Show Gist options
  • Save akwodkiewicz/879a905f2f55f57e83eb801752e19047 to your computer and use it in GitHub Desktop.
Save akwodkiewicz/879a905f2f55f57e83eb801752e19047 to your computer and use it in GitHub Desktop.
public static Tuple<Point, Point> FindClosestPoints(List<Point> points, out double minDistance)
{
var minDist = double.PositiveInfinity;
int lastDeleted = 0;
Point a = new Point();
Point b = new Point();
SortedSet<Point> tree = new SortedSet<Point>(new ByY());
var pointsArray = points.ToArray();
Array.Sort(pointsArray, new ByX());
for (int i = 0; i < points.Count; i++)
{
var p = pointsArray[i];
for (int j = lastDeleted; j < i; j++)
{
var q = pointsArray[j];
if (p.x - q.x > minDist)
{
lastDeleted = j;
tree.Remove(q);
}
}
var result = tree.GetViewBetween(new Point(p.x, p.y - minDist), new Point(p.x, p.y + minDist));
foreach (var q in result)
{
if (Point.Distance(p, q) < minDist)
{
a = p;
b = q;
minDist = Point.Distance(p, q);
}
}
tree.Add(p);
}
minDistance = minDist;
return new Tuple<Point, Point>(a, b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment