Skip to content

Commit 9f93375

Browse files
committed
Rectangle intersection
1 parent 953b143 commit 9f93375

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

elements-of-programming-interviews/cpp/rectangle_intersection.cc

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,51 @@
44
#include "test_framework/generic_test.h"
55
#include "test_framework/serialization_traits.h"
66
struct Rect {
7+
// x and y are bottom left corner
78
int x, y, width, height;
89
};
910

10-
Rect IntersectRectangle(const Rect& r1, const Rect& r2) {
11-
// TODO - you fill in here.
12-
return {0, 0, 0, 0};
13-
}
1411
bool operator==(const Rect& r1, const Rect& r2) {
1512
return std::tie(r1.x, r1.y, r1.width, r1.height) ==
1613
std::tie(r2.x, r2.y, r2.width, r2.height);
1714
}
1815

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+
1952
namespace test_framework {
2053
template <>
2154
struct SerializationTrait<Rect> : UserSerTrait<Rect, int, int, int, int> {

elements-of-programming-interviews/problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ problem_mapping = {
156156
},
157157
"4.11 Rectangle intersection": {
158158
"C++: rectangle_intersection.cc": {
159-
"passed": 0,
159+
"passed": 10000,
160160
"total": 10000
161161
},
162162
"Java: RectangleIntersection.java": {

0 commit comments

Comments
 (0)