TAHA SULTAN TEMURI
TAHA SULTAN TEMURI

Reputation: 5161

Creating List of Pair type (Value,Value) in C#

I would like to create pair of list of some int values like

(3,4) , (5,4) ,(5,1)....(n,n)

then match each with single target like

(1,1)

I need to compare each value of list with target (1,1) , so that it should print the most nearest point to (1,1)

Expected Result.

(3,4)

What is Nearest

Nearest means , lets say if we have number 4,5,6,7,8 and I want to find most nearest number to 12 so answer will be 8 because it takes 4 to reach 12 but 4+n moves to reach 12 from other, so in same way unlike single value I have pair of values (n,n).... and compare with (n,n)

What I Have Tried Using 2D Array

positions = new int[3][,] 
{
new int[,] { {3,4} },
new int[,]{ {5,4}},
 new int[,] { {5,1} }

};

This gives me

3,4

5,4

5,1

Now I need to compare each value with (1,1) but I dont know any proper data structure through which I can easily store my list and compare each with (1,1).

Please help

Upvotes: 0

Views: 3758

Answers (2)

Julian
Julian

Reputation: 36710

C# 7 has tuples and I think you're looking for that!

E.g. a list of tuples:

var positions = new List<(int x, int y)>
{
    (3,4),
    (5,4),
    (5,1)
};

You could find the "closest" for example like this:

(int x, int y) value = (1, 1);
var closest = positions.OrderBy(p => (p.x - value.x) + (p.y - value.y)).First(); // finds (5,1)

Upvotes: 6

Matt
Matt

Reputation: 1757

I am going to assume that these points are points in a plane and we can use Pythagorean theorem to get the distance between two points.

With that assumption out of the way, I would create a new class to hold the x/y positional data and a DistanceBetween method which runs the Pythagorean theorem.

static void Main(string[] args)
{
    List<Point> points = new List<Point>
    {
        new Point(3, 4),
        new Point(5, 4),
        new Point(5, 1)
    };

    Point closestPoint = points.OrderBy(point => point.DistanceFromPoint(new Point(1, 1))).FirstOrDefault();

    Console.WriteLine($"The closest point to 1,1 is {closestPoint.PosX},{closestPoint.PosY}");
    Console.ReadLine();
}

private class Point
{
    public Point(int posX, int posY)
    {
        PosX = posX;
        PosY = posY;
    }

    public int PosX { get; set; }
    public int PosY { get; set; }

    public double DistanceFromPoint(Point otherPoint)
    {
        return Math.Sqrt(Math.Pow((otherPoint.PosX - PosX), 2) + Math.Pow((otherPoint.PosY - PosY), 2));
    }
}

Upvotes: 4

Related Questions