Gimmeursocks
Gimmeursocks

Reputation: 3

How to compute the position of the 4th corner of a rectangle?

I have 3 corners of an axis aligned box, I must find the 4th corner.

How can I compute it more efficiently:

if (loc[0].first != loc[1].first && loc[0].first != loc[2].first)
    x = loc[0].first;
else if (loc[1].first != loc[0].first && loc[1].first != loc[2].first)
    x = loc[1].first;
else
    x = loc[2].first;

if (loc[0].second != loc[1].second && loc[0].second != loc[2].second)
    y = loc[0].second;
else if (loc[1].second != loc[0].second && loc[1].second!=loc[2].second)
    y = loc[1].second;
else 
    y = loc[2].second;

Upvotes: 0

Views: 131

Answers (2)

user1196549
user1196549

Reputation:

If the points are guaranteed to be perfectly aligned vertically or horizontally, the fourth corner is found at the unique abscissa and unique ordinate.

if X0 == X1:
    X3= X2
elif X0 == X2:
    X3= X1
else:
    X3= X0

You can't do this in less than two comparisons, because the outcome depends on the three values.

Same code on Y, independently. Or, you can even spare a comparison on Y, because if two X's are known to be equal, the corresponding Y's are perforce different. Hence on average a total of 8/3 comparisons.


If you are after the ordered axis-aligned bounding box, take the minimum and maximum of the abscissas and ordinates separately.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217930

Assuming you have 2 identical (integral) numbers and a third one, xor might give you the expected one:

x = loc[0].first  ^ loc[1].first  ^ loc[2].first;
y = loc[0].second ^ loc[1].second ^ loc[2].second;

if type is not integral (so no xor), it seems more readable to check for equality (that also does one check for equality instead of 2 checks for inequality by test):

if (loc[0].first == loc[1].first)
    x = loc[2].first;
else if (loc[0].first == loc[2].first)
    x = loc[1].first;
else // loc[1].first == loc[2].first
    x = loc[0].first;

Upvotes: 3

Related Questions