Skip to content

Instantly share code, notes, and snippets.

@safeng
Created October 8, 2014 03:12
Show Gist options
  • Save safeng/e0bf25eb7a974decf638 to your computer and use it in GitHub Desktop.
Save safeng/e0bf25eb7a974decf638 to your computer and use it in GitHub Desktop.
Check whether xy-aligned rectangle r1 and r2 intersects. If it is, return the intersected range.
#include <iostream>
using namespace std;
struct Rectangle {
int x, y, width, height;
};
bool is_intersect(const Rectangle &r1, const Rectangle &r2);
Rectangle rect_intersect(const Rectangle &r1, const Rectangle &r2)
{
if (is_intersect(r1, r2)) {
return {std::max(r1.x, r2.x), std::max(r1.y, r2.y),
std::min(r1.x + r1.width, r2.x + r2.width) - std::max(r1.x, r2.x),
std::min(r1.y, r2.y) - std::max(r1.y - r1.height, r2.y - r2.height)};
} else {
return {0, 0, -1, -1};
}
}
// determine whether a rectangle is NOT overlap over another
bool is_intersect(const Rectangle &r1, const Rectangle &r2)
{
return !(r1.x + r1.width < r2.x || r2.x + r2.width < r1.x ||
r1.y - r1.height > r2.y || r2.y - r2.height > r1.y);
}
int main()
{
Rectangle r1 = {0, 4, 3, 4}, r2 = {2, 5, 4, 5};
Rectangle inter = rect_intersect(r1, r2);
cout << inter.x << " " << inter.y << " " << inter.width << " " << inter.height << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment