This is an interesting problem. You can change the squares center and it's size. That might make you think that the square should record it's center and size, but I suggest that you don't go that way. Instead, record the square's top, left, bottom and right edges. It will make ModificaDCentura and ModificaLatura a little harder, but Interesecteaza() will be
much easier.
So for a start, class square should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class square
{
int top, left, bottom, right;
public:
square() : top(0), left(0), bottom(0), right(0) {}
void ModificaCentru(int x, int y);
void ModificaLatura(int sz);
bool Interesecteaza(const square &s2);
bool InInterior(int x, int y);
friend ostream & operator <<(ostream &, const square &sq);
};
ostream &operator<<(ostream &os, const square &sq)
{
os << '(' << sq.left << ',' << sq.top << ") to"
<< '(' << sq.right << ',' << sq.bottom << ")\n";
return os;
};
|
Note that I've added an output operator that displays the top-left and bottom-right corners of the square. This will really help in debugging. Add temporary code to main() that will print out the squares:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
int
main()
{
square p1;
p1.ModificaCentru(0, 0);
p1.ModificaLatura(10);
cout << "p1= " << p1;
if (p1.InInterior(4, 4))
cout << "yes\n";
else
cout << "no\n";
if (p1.InInterior(6, 4))
cout << "yes\n";
else
cout << "no\n";
if (p1.InInterior(-1, 4))
cout << "yes\n";
else
cout << "no\n";
square p2;
p2.ModificaCentru(-5, -5);
p2.ModificaLatura(2);
cout << "p2= " << p2;
if (p1.Interesecteaza(p2))
cout << "yes\n";
else
cout << "no\n";
p2.ModificaCentru(7, 7);
cout << "p2= " << p2;
if (p1.Interesecteaza(p2))
cout << "yes\n";
else
cout << "no\n";
p2.ModificaLatura(4);
cout << "p2= " << p2;
if (p1.Interesecteaza(p2))
cout << "yes\n";
else
cout << "no\n";
system("pause");
return 0;
}
|
Okay, now comes the hard part. Sit down with a pencil and paper and figure out what ModificaCentru() and ModificaLatura() should do. Then translate that to code Run the program and look at the output from the bold lines above.
Don't pay any attention to whether the other output is right. Just make sure that the square is modified correctly.
Once you have the square getting set right, you can try the intersection methods. Here are a couple of pointers:
- a point is inside a square if its x coordinate is between the left and right edges of the square, and it's y coordinate is between the top and bottom edges.
To see if they intersect, notice that if they don't intersect then one square must lie above, below, to the left or to the right of the other square. Check these 4 conditions and if they are all false, then the squares intersect.