I have a list of tuples List<(double X, double Y)> Data
and a
variable of type double
. It is required to add to the array (double, double)[] output
the 4 elements closest to a
. They need to be found among all Data.X
. It is necessary to arrange data in order of distance from a
.
Example:
Input:
a = 15.5;
{(-10, 1),
(12, 2),
(14, 3),
(16, 4),
(50, 5)}
Output:
output [0] = (16, 4);
output [1] = (14, 3);
output [2] = (12, 2);
output [3] = (-10, 1);
EDIT:My current solution:
class CubicSpline
{
List<(double X, double Y)> Data { get; set; }
public CubicSpline(List<(double X, double Y)> data)
{
Data = data;
}
/// <summary>
/// Method for finding 4 nearest neighbors for x.
/// </summary>
public (double, double)[] FindNeighbours(double x)
{
var temp = Data.OrderBy(b => Math.Abs(x - b.X)).ToList();
(double, double)[] output = new (double, double)[4];
for(int i = 0; i < 4; i++)
{
output[i] = temp[i];
}
return output;
}
}
Since you started with LINQ, you can use some other LINQ methods to compute the result:
public (double, double)[] FindNeighbours(double x) =>
Data.OrderBy(b => Math.Abs(x - b.X)).Take(4).ToArray();
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.