I have a polygon defined by the following vertices, represented by their X
and Y
values and sorted in a counter-clockwise order:
{ 20, 10},
{110, 10},
{100, 40},
{ 80, 50},
{ 40, 50},
{ 20, 30}
I also have a List<int>
containing their indices . I can zip the two lists together if I want to reorder the points while keeping track of the original order.
How should i go about getting the closest points above and below a given point, so that entering:
point = {115, 30}
Would output:
closestAbove = {100, 40}, index = 2
closestBelow = {110, 10}, index = 1
Performance isn't critical , so iterating multiple times through the list is not an issue.
First, let's come to terms:
// I've put named tuples, but you can use a different type for points
(double x, double y)[] points = new (double x, double y)[] {
( 20, 10 ),
( 110, 10 ),
( 100, 40 ),
( 80, 50 ),
( 40, 50 ),
( 20, 30 ),
};
// Euclidian distance
Func<(double x, double y), (double x, double y), double> distance = (p1, p2) =>
Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
(double x, double y) point = (115, 30);
And then query with a help of Linq ; even if ArgMin
is not implemented by standard Linq, it can be easily done with a help of Aggregate
:
var above = points
.Select((p, index) => new {
p,
index
})
.Where(item => item.p.y > point.y) // change to < for below
.Aggregate((distance: 0.0,
x: 0.0,
y: 0.0,
index: -1),
(s, a) => s.index < 0 || s.distance > distance(point, a.p)
? (distance(point, a.p), a.p.x, a.p.y, a.index)
: s);
Let's have a look:
Console.Write($"Point #{above.index} ({above.x}, {above.y}) is the closest point to the ({point.x}, {point.y})");
Outcome:
Point #2 (100, 40) is the closest point to the (115, 30)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.