question

Given the top-left and bottom-right coordinates of two axis-aligned rectangles, write a conditional statement to determine if they overlap.

First write conditions if rectangles do not overlap. Then look into De Morgan's law.

Let's define two rectangles A & B with each top-left corner represented by (x1, y1) and bottom-right (x2, y2). There are four conditions that if true, we know no overlap exists:

Conditions

1. If A's left edge is to the right of B's right edge

2. If A's right edge is to the left of B's left edge

3. If A's top edge is below B's bottom edge

4. If A's bottom edge is above B's top edge

So if

In words:

1. If A's left edge is to the left of B's right edge

AND

2. If A's right edge is to the right of B's left edge

AND

3. If A's top edge is above B's bottom edge

AND

4. If A's bottom edge is below B's top edge

Boiling down to the following conditional statement:

If you're having trouble visualizing this, check out this great interactive demo.

Thoughts or alternate solution? Let us know in the comments below!

Conditions

1. If A's left edge is to the right of B's right edge

2. If A's right edge is to the left of B's left edge

3. If A's top edge is below B's bottom edge

4. If A's bottom edge is above B's top edge

So if

`C1 OR C2 OR C3 OR C4`

is true, then the rectangles do not overlap. Using De Morgan's law, we know that if the rectangles overlap the following will evaluate true: `!C1 AND !C2 AND !C3 AND !C4`

In words:

1. If A's left edge is to the left of B's right edge

AND

2. If A's right edge is to the right of B's left edge

AND

3. If A's top edge is above B's bottom edge

AND

4. If A's bottom edge is below B's top edge

Boiling down to the following conditional statement:

```
```**if** ((A.X1 < B.X2) && (A.X2 > B.X1) && (A.Y1 < B.Y2) && (A.Y2 > B.Y1)

rectangles overlap

If you're having trouble visualizing this, check out this great interactive demo.

Thoughts or alternate solution? Let us know in the comments below!