Pregunta de entrevista de Cryptic Studios

Given two rectangles on a plane, determine if they are overlapping.

Respuesta de la entrevista

Anónimo

11 abr 2015

// Check if the rects overlap. // Checks 4 conditions: // 1. Is the right side of one rect to the right of the other's left bound? (if not, this rect is completely left of the other) // 2. Is the left side of that same rect to the left of the other's right bound? (if not, this rect is completely right of the other) // 3. Is the top side of that same rect above the bottom side of the other's? (if not, this rect is completely below the other) // 4. Is the bottom side of that same rect below the top side of the other's? (if not, this rect is completely above the other) // // Note that this checks all cases: // Either rect will always be totally to the right, totally to the left, or horizontally overlapping with the other. // Either rect will always be totally above, totally below, or vertically overlapping with the other. // // By process of elimination, we simply need to check the failure cases // (completely left, completely right, completely above, and completely below). // If none of those are true when comparing either rect to the other, then the two rects overlap. // // rect0: the first rect to check for overlap // rect1: the second rect to check for overlap bool checkRectsOverlap(Rect rect0, Rect rect1) { return (rect0.xMax > rect1.xMin) && (rect0.xMin rect1.yMin) && (rect0.yMin < rect1.yMax); }