AdminBenni
AdminBenni

Reputation: 361

Check which 2d array elements are closer to each other if the index is represented as x y positions

So I have a two dimensional array that holds some value that doesn't matter. Let's say that the indexes represent x and y positions on a grid and that I have three points on that grid: The main point and two extra points how do I check which extra point is closest to the main point. This is the code I tried but it didn't seem to quite work.

if(abs(mainX - extra1X) + abs(mainY - extra1Y) < abs(mainX - extra2X) + abs(mainY - extra2Y))
{
cout << "Extra point 1 is closer" << endl;
}
else if(abs(mainX - extra1X) + abs(mainY - extra1Y) > abs(mainX - extra2X) + abs(mainY - extra2Y))
{
cout << "Extra point 2 is closer" << endl;
}
else
{
cout << "They are equally close" << endl;
}

All help is greatly appreciated :)

Upvotes: 0

Views: 242

Answers (2)

Bback.Jone
Bback.Jone

Reputation: 61

If you don't need distance but just need less or more, I want to recommend to just use square of the two number. you can try this

double dSquare = (mainX - extra1X) * (mainX - extra1X) + (mainY - extra1Y)     * (mainY - extra1Y); 
double dSquare = (mainX - extra1X) * (mainX - extra1X) + (mainY - extra1Y) *(mainY - extra1Y);
if(dSquare > dSquare2)
   cout << "point 2 is closer" << endl;
else if(dSquare < dSquare2)
   cout << "point 1 is closer" << endl;
else
   cout << "two point are on the same distance from the main point" << endl;

Upvotes: 1

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

You are looking for The Distance Formula:

double Distance = sqrt(pow((X1 - X2), 2) + pow((Y1 - Y2), 2));

Implement and execute that for both points, then check the value of Distance for each point to determine which point is closer.

This should work:

double DistanceOne = sqrt(pow((MainX - ExtraXone), 2) + pow((MainY - ExtraYone), 2));
double DistanceTwo = sqrt(pow((MainX - ExtraXtwo), 2) + pow((MainY - ExtraYtwo), 2));

if(DistanceOne < DistanceTwo)
    cout << "Point 1 is closer.\n";
else if (DistanceOne > DistanceTwo)
    cout << "Point 2 is closer.\n";
else
    cout << "Points 1 and 2 are on the same distance from Point Main.\n";

Upvotes: 2

Related Questions