Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find if 4 points on a plane form a rectangle?

Can somebody please show me in C-style pseudocode how to write a function (represent the points however you like) that returns true if 4-points (args to the function) form a rectangle, and false otherwise?

I came up with a solution that first tries to find 2 distinct pairs of points with equal x-value, then does this for the y-axis. But the code is rather long. Just curious to see what others come up with.

like image 747
pete Avatar asked Feb 20 '10 19:02

pete


People also ask

How do you find a rectangle on a coordinate plane?

The area of rectangle can be found by multiplying the width and length of the rectangle. To find the length of the rectangle compare the x values of two of the coordinates: Since the length is . To find the width of the rectangle we need to look at the y coordinates of two of the points.


2 Answers

  • find the center of mass of corner points: cx=(x1+x2+x3+x4)/4, cy=(y1+y2+y3+y4)/4
  • test if square of distances from center of mass to all 4 corners are equal
bool isRectangle(double x1, double y1,                  double x2, double y2,                  double x3, double y3,                  double x4, double y4) {   double cx,cy;   double dd1,dd2,dd3,dd4;    cx=(x1+x2+x3+x4)/4;   cy=(y1+y2+y3+y4)/4;    dd1=sqr(cx-x1)+sqr(cy-y1);   dd2=sqr(cx-x2)+sqr(cy-y2);   dd3=sqr(cx-x3)+sqr(cy-y3);   dd4=sqr(cx-x4)+sqr(cy-y4);   return dd1==dd2 && dd1==dd3 && dd1==dd4; } 

(Of course in practice testing for equality of two floating point numbers a and b should be done with finite accuracy: e.g. abs(a-b) < 1E-6)

like image 54
Curd Avatar answered Nov 11 '22 20:11

Curd


struct point {     int x, y; }  // tests if angle abc is a right angle int IsOrthogonal(point a, point b, point c) {     return (b.x - a.x) * (b.x - c.x) + (b.y - a.y) * (b.y - c.y) == 0; }  int IsRectangle(point a, point b, point c, point d) {     return         IsOrthogonal(a, b, c) &&         IsOrthogonal(b, c, d) &&         IsOrthogonal(c, d, a); } 

If the order is not known in advance, we need a slightly more complicated check:

int IsRectangleAnyOrder(point a, point b, point c, point d) {     return IsRectangle(a, b, c, d) ||            IsRectangle(b, c, a, d) ||            IsRectangle(c, a, b, d); } 
like image 24
Vlad Avatar answered Nov 11 '22 19:11

Vlad