-
Notifications
You must be signed in to change notification settings - Fork 3
/
187_Google_Find_If_Rectangles_Overlap.py
executable file
·65 lines (53 loc) · 1.8 KB
/
187_Google_Find_If_Rectangles_Overlap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
This problem was asked by Google.
You are given given a list of rectangles represented by min and max x- and y-coordinates.
Compute whether or not a pair of rectangles overlap each other.
If one rectangle completely covers another, it is considered overlapping.
For example, given the following rectangles:
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
},
{
"top_left": (-1, 3),
"dimensions": (2, 1)
},
{
"top_left": (0, 5),
"dimensions": (4, 3)
}
return true as the first and third rectangle overlap each other.
"""
from itertools import combinations
def is_overlapping(rec1, rec2):
top_left_x = max(rec1["top_left"][0], rec2["top_left"][0])
top_left_y = min(rec1["top_left"][1], rec2["top_left"][1])
bottom_right_x = min(rec1["top_left"][0] + rec1["dimensions"][0], rec2["top_left"][0] + rec2["dimensions"][0])
bottom_right_y = max(rec1["top_left"][1] - rec1["dimensions"][1], rec2["top_left"][1] - rec2["dimensions"][1])
if top_left_x > bottom_right_x or bottom_right_y > top_left_y:
return False
elif (bottom_right_x - top_left_x) * (top_left_y - bottom_right_y) == 0:
# intersection area is zero. Only on edge on top an other
return False
return True
def check_overlapping_pair(rectangles):
for rec1, rec2 in combinations(rectangles, 2):
if is_overlapping(rec1, rec2):
return True
return False
if __name__ == '__main__':
rectangels= [
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
},
{
"top_left": (-1, 3),
"dimensions": (2, 1) # width, height
},
{
"top_left": (0, 5),
"dimensions": (4, 3) # width, height
}
]
assert check_overlapping_pair(rectangels) == True