-4

I got a problem on this c++ questions.

The background is that we need to let the user to type in the number of stones in a farm, then they will type in the coordinates of the stone. After typing in the coordinates, we need to check whether they can form a rectangle or not.

Here is the sample input and output:

9(number of rocks) coordinates: the output is two 2 2 2 5 4 2 4 4 9 2 9 4 9 6 10 4 10 6

However , I don't know how to find out rectangles. I got some problems in comparing there coordinates, can you guys help me??

Amit
  • 13,134
  • 17
  • 77
  • 148
killer2318
  • 29
  • 8
  • For every set of four vertices check if it forms rectangle or not. Although there arre better methods but this will work for you as input size is small.For rectangle check you can compare length of diagonals. – Ashwani Nov 19 '14 at 05:58
  • The question is for the algorithm and logic rather than for C++ programming. Still I have not removed the C++ tag, let the community decide.. – Amit Nov 19 '14 at 06:03

2 Answers2

0

check this clever solution from this link

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;
    }
Community
  • 1
  • 1
Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
0

Constraint 1: center for both diagonals should be same. Constraint 2: dot product of two lines starting from one vertex should be zero.

bool isRectangle(double x1, double y1,
                     double x2, double y2,
                     double x3, double y3,
                     double x4, double y4)
    {
      bool bCenterEqual = ((x1+x3)==(x2+x4) && (y1+y3)==(y2+y4));
      if(!bCenterEqual)
        return false;
     if((x2-x1)*(x4-x1)+(y2-y1)*(y4-y1)!=0)
        return false;
    return true;    
    }