/*
Axis‑aligned rectangles are simply rectangles whose edges are parallel to the
coordinate axes — meaning their sides are horizontal and vertical.
That single assumption makes the overlap test dramatically simpler and faster.
*/
/*
Rectangle overlap detection (axis-aligned)
Each rectangle is defined by:
- x, y : coordinates of its top-left corner
- w, h : width and height
Two rectangles DO NOT overlap if any separating condition is true:
- One is completely to the left of the other
- One is completely to the right of the other
- One is completely above the other
- One is completely below the other
Otherwise, they overlap.
This is the standard O(1) test for axis-aligned rectangles.
*/
class Rect {
x: number; // top-left X
y: number; // top-left Y
w: number; // width
h: number; // height
constructor(x: number, y: number, w: number, h: number) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
}
/*
Returns true if rectangles A and B overlap.
*/
function rectanglesOverlap(A: Rect, B: Rect): boolean {
// Compute edges of A
const A_left: number = A.x;
const A_right: number = A.x + A.w;
const A_top: number = A.y;
const A_bottom: number = A.y + A.h;
// Compute edges of B
const B_left: number = B.x;
const B_right: number = B.x + B.w;
const B_top: number = B.y;
const B_bottom: number = B.y + B.h;
// Separating conditions:
if (A_right <= B_left) return false; // A is left of B
if (B_right <= A_left) return false; // B is left of A
if (A_bottom <= B_top) return false; // A is above B
if (B_bottom <= A_top) return false; // B is above A
return true; // Otherwise, they overlap
}
// Example rectangles
const A: Rect = new Rect(10, 10, 30, 20); // Example rectangle A
const B: Rect = new Rect(25, 15, 40, 25); // Overlaps A
const C: Rect = new Rect(100, 100, 10, 10); // Does not overlap A
console.log("A vs B overlap? " + (rectanglesOverlap(A, B) ? "YES" : "NO"));
console.log("A vs C overlap? " + (rectanglesOverlap(A, C) ? "YES" : "NO"));
/*
run:
A vs B overlap? YES
A vs C overlap? NO
*/