Use the distance formula: distance = sqrt( (x1-x2)^2 + (y1-y2)^2) )
Good old Pythagoras!
Using your sample data I was able to whip up a quick program that spit this out:
Code:
Cat is at: (2,2)
Dog is at: (1,1)
There are 4 trees: (0,1) (1.5,1.5) (2.5,2.9) (0,0.5)
The closest tree to the cat is: (1.5,1.5)
The dog is 1.4142135623731 units from the cat.
The cat is 0.707106781186548 units from the closest tree.
The cat will not escape from the dog.
Since I wrote it in C# because this is the C# forum, but you need to write it in C, I guess there's no harm in posting the code to see how I did it:
Code:
class Program
{
struct Point
{
double X;
double Y;
public Point(double x, double y)
: this()
{
X = x;
Y = y;
}
public double DistanceFrom(Point other)
{
return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
}
public static Point FromLine(string line)
{
string[] parts = line.Split(' ');
return new Point(double.Parse(parts[0]), double.Parse(parts[1]));
}
public override string ToString()
{
return "(" + X + "," + Y + ")";
}
}
static void Main(string[] args)
{
TextReader reader = new StreamReader("..\\CatAndDog.dat");
Point cat = Point.FromLine(reader.ReadLine());
Point dog = Point.FromLine(reader.ReadLine());
int numTrees = int.Parse(reader.ReadLine());
Point[] trees = new Point[numTrees];
for (int i = 0; i < numTrees; ++i)
trees[i] = Point.FromLine(reader.ReadLine());
reader.Close();
Console.WriteLine("Cat is at: {0}", cat);
Console.WriteLine("Dog is at: {0}", dog);
Console.Write("There are {0} trees:", trees.Length);
foreach (Point tree in trees)
Console.Write(" {0}", tree);
Console.WriteLine();
Point closestTree = trees.OrderBy(t => t.DistanceFrom(cat)).First();
Console.WriteLine("The closest tree to the cat is: {0}", closestTree);
Console.WriteLine("The dog is {0} units from the cat.", dog.DistanceFrom(cat));
Console.WriteLine("The cat is {0} units from the closest tree.", cat.DistanceFrom(closestTree));
Console.WriteLine("The cat will{0} escape from the dog.", (cat.DistanceFrom(closestTree) * 2 < dog.DistanceFrom(cat)) ? "" : " not");
}
}