|
4 | 4 | #include "test_framework/generic_test.h" |
5 | 5 | #include "test_framework/serialization_traits.h" |
6 | 6 | struct Rect { |
| 7 | + // x and y are bottom left corner |
7 | 8 | int x, y, width, height; |
8 | 9 | }; |
9 | 10 |
|
10 | | -Rect IntersectRectangle(const Rect& r1, const Rect& r2) { |
11 | | - // TODO - you fill in here. |
12 | | - return {0, 0, 0, 0}; |
13 | | -} |
14 | 11 | bool operator==(const Rect& r1, const Rect& r2) { |
15 | 12 | return std::tie(r1.x, r1.y, r1.width, r1.height) == |
16 | 13 | std::tie(r2.x, r2.y, r2.width, r2.height); |
17 | 14 | } |
18 | 15 |
|
| 16 | +bool pointIntervalIntersect(const int p, const int l, const int r) { |
| 17 | + // p in [l,r]? |
| 18 | + return l <= p && p <= r; |
| 19 | +} |
| 20 | + |
| 21 | +bool cornerOverlap1D(const int aLeft, const int aRight, const int bLeft, |
| 22 | + const int bRight) { |
| 23 | + return pointIntervalIntersect(bLeft, aLeft, aRight) || |
| 24 | + pointIntervalIntersect(bRight, aLeft, aRight) || |
| 25 | + pointIntervalIntersect(aLeft, bLeft, bRight) || |
| 26 | + pointIntervalIntersect(aRight, bLeft, bRight); |
| 27 | +} |
| 28 | + |
| 29 | +Rect IntersectRectangle(const Rect& r1, const Rect& r2) { |
| 30 | + int r1Left = r1.x; |
| 31 | + int r1Down = r1.y; |
| 32 | + int r1Right = r1.x + r1.width; |
| 33 | + int r1Up = r1.y + r1.height; |
| 34 | + |
| 35 | + int r2Left = r2.x; |
| 36 | + int r2Down = r2.y; |
| 37 | + int r2Right = r2.x + r2.width; |
| 38 | + int r2Up = r2.y + r2.height; |
| 39 | + |
| 40 | + if (!(cornerOverlap1D(r1Left, r1Right, r2Left, r2Right) && |
| 41 | + cornerOverlap1D(r1Down, r1Up, r2Down, r2Up))) { |
| 42 | + return {0, 0, -1, -1}; |
| 43 | + } |
| 44 | + std::vector<int> yVals{r1Up, r1Down, r2Up, r2Down}; |
| 45 | + std::sort(yVals.begin(), yVals.end()); |
| 46 | + std::vector<int> xVals{r1Left, r1Right, r2Left, r2Right}; |
| 47 | + std::sort(xVals.begin(), xVals.end()); |
| 48 | + |
| 49 | + return {xVals[1], yVals[1], xVals[2] - xVals[1], yVals[2] - yVals[1]}; |
| 50 | +} |
| 51 | + |
19 | 52 | namespace test_framework { |
20 | 53 | template <> |
21 | 54 | struct SerializationTrait<Rect> : UserSerTrait<Rect, int, int, int, int> { |
|
0 commit comments