// Prog: rectangles.cpp // checks whether two rectangles intersect #include #include // PRE: [a1, b1], [a2, b2] are (generalized) intervals, // with [a,b] := [b,a] if a>b // POST: returns true if [a1, b1],[a2, b2] intersect bool intervals_intersect (int a1, int b1, int a2, int b2) { return std::max(a1, b1) >= std::min(a2, b2) && std::min(a1, b1) <= std::max(a2, b2); } // PRE: (x1, y1, w1, h1), (x2, y2, w2, h2) are rectangles, where // w1, h1, w2, h2 may be negative // POST: returns true if (x1, y1, w1, h1),(x2, y2, w2, h2) intersect bool rectangles_intersect (int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) { return intervals_intersect (x1, x1 + w1, x2, x2 + w2) && intervals_intersect (y1, y1 + h1, y2, y2 + h2); } int main () { std::cout << "Enter two rectangles in the format x y w h each\n"; int x1, y1, w1, h1; std::cin >> x1 >> y1 >> w1 >> h1; int x2, y2, w2, h2; std::cin >> x2 >> y2 >> w2 >> h2; bool clash = rectangles_intersect (x1,y1,w1,h1,x2,y2,w2,h2); if (clash) std::cout << "intersection!\n"; else std::cout << "no intersection!\n"; return 0; }