Lorris
Lorris

Reputation: 73

How to know if a list of coordinates forms a rectangle?

I am currently trying to figure out how to check if my list, for instance this :

[[0, 0], [0, 1], [1, 0], [1, 1]]

forms a rectangle like this :

A B
C D

with A, B, C and D respectivly [0, 0], [0, 1], [1, 0] and [1, 1] of the list. The idea is of course to do something generic, so something like :

[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0]]

==> X X X X
    X

should return false.

Is there any mathematic concept that I can use ? Or maybe I ask this question the wrong way, and there is an obvious way that I can't see ! Anyway, any help is greatly appreciated !

Upvotes: 2

Views: 3906

Answers (3)

user7345804
user7345804

Reputation:

A different solution you can try is incorporating the orthogonality of the rectangles line segments. If you import the math module or numpy module, you can check to see if each consecutive pair of line segments forms a right angle. You can extend this idea into properties of diagonals, or can use the diagonals to find out if the corner angles are right angles. You can also amend the code and apply the distance formula; if the lengths of each line in the rectangle (obtained via distance formula) are all equal to each other, then the rectangle is a square.

Upvotes: 0

TemporalWolf
TemporalWolf

Reputation: 7952

If they have to be inline with the coordinate plane:

def isRect(coords):
    if len(coords) != 4:
        return False
    tA, tB, tC, tD = sorted(coords)
    return tA[0] == tB[0] and tC[0] == tD[0] and tA[1] == tC[1] and tB[1] == tD[1]

which is enforcing [a c] [a d] [b c] [b d] by sorting them by x, then y, then doing a boolean comparison.

Upvotes: 2

Prune
Prune

Reputation: 77847

Yes, there are several properties you can harness to get this done.

First, of course, is that a rectangle has exactly four vertices; your second list should be rejected on those grounds alone. :-)

Otherwise, you can check the slopes of the sides. A parallelogram has opposite sides parallel. The slope of a line segment from (x1, y1) to (x2, y2) is

m = (y2 - y1) / (x2 - x1)

Once you verify that you have a parallelogram, you need to check that the adjacent sides are perpendicular. Such lines have slopes whose product is -1. So if you've computed the four slopes m1 through m4, and verified m1=m3 and m2=m4, all that's left is to check any one corner:

if m1*m2 = -1:
    ...

Note that your equality checks here shouldn't require an exact match; float rounding can give you tiny differences. Instead, perhaps

if abs(m1*m2 + 1) < 0.000001:

Another property that might give you a more direct result is that a figure is a rectangle if and only if the diagonals bisect each other. Take your two diagonals and find the midpoints.

xmid = (x1 + x2)/2
ymid = (y1 + y2)/2

If the two midpoints are the same (or very close), then you have a rectangle.

Upvotes: 2

Related Questions