Kevin Meier - 8 months ago 69

Python Question

I have a set of rectangles and i need to calculate the manhatten distance between them. I already tried to implement it, but the code blow up and did not work well.

Maybe someone could help me with some smart (and efficient) formulas which could be used to calculate the distance between two rectangles?

Examples:

The distance between

`A`

`B`

`1`

`A`

`C`

`2`

I use python to implement everything. If already a function exists (e.g. in scipy) and someone knows it, this would also be great.

Thank you

Answer

I suggest, you work with the central points of rectangles and rectangle widths to compute the distances. You mainly have to figure out which corners (edges) of rectangles to use for computation. everything else is simple. A quick example:

```
class Rect:
def __init__(self,cpt,w,h):
self.x = cpt[0]
self.y = cpt[1]
self.w = w
self.h = h
def dist(self,other):
#overlaps in x or y:
if abs(self.x - other.x) <= (self.w + other.w):
dx = 0;
else:
dx = abs(self.x - other.x) - (self.w + other.w)
#
if abs(self.y - other.y) <= (self.h + other.h):
dy = 0;
else:
dy = abs(self.y - other.y) - (self.h + other.h)
return dx + dy
#example:
A = Rect((0,0),2,1)
B = Rect((4,5),1,2)
C = Rect((-1,-5),1,1)
print(A.dist(C))
print(A.dist(B))
print(B.dist(C))
```

Source (Stackoverflow)