C#/Winform

[C#] Point 들간 거리 순으로 정렬하기 / Point List Sort

kjun.kr 2022. 4. 22. 09:20
728x90
728x170
Func<Point, List<Point>, int> sortDistance = (point, pointList) =>
{
    KeyValuePair<double, int> smallestDistance = new KeyValuePair<double, int>();
    for (int i = 0; i < pointList.Count; i++)
    {
        double distance = Math.Sqrt(Math.Pow(point.X - pointList[i].X, 2) + Math.Pow(point.Y - pointList[i].Y, 2));

        if (i == 0)
        {
            smallestDistance = new KeyValuePair<double, int>(distance, i);
        }
        else
        {
            if (distance < smallestDistance.Key)
            {
                smallestDistance = new KeyValuePair<double, int>(distance, i);
            }
        }
    }

    return smallestDistance.Value;
};

var inputList = new List<Point>() { new Point(2,7), new Point(12, 5), new Point(0, 3), new Point(5, 10), new Point(4, 5) };
List<Point> output = new List<Point>();
output.Add(inputList[sortDistance(new Point() { X = 0, Y = 0 }, inputList)]);
inputList.Remove(output[0]);
int x = 0;
for (int i = 0; i < inputList.Count + x; i++)
{
    output.Add(inputList[sortDistance(output[output.Count - 1], inputList)]);
    inputList.Remove(output[output.Count - 1]);
    x++;
}

결과

728x90
그리드형