Distance between point and rectangular box without case logic

Assuming you have a point (x,y) and a rectangle parallel to x and y axis defined by its upper left and lower right corner. How can we calculate its distance without using case logic?

P = (x,y)
A = { (x1,y1), (x2,y2) }

The answer is:

dx = max(A.x1 - p.x, 0, p.x - A.x2)
dy = max(A.y1 - p.y, 0, p.y - A.y2)
distance = sqrt(dx*dx + dy*dy)

Its very tricky.

Here is a great analysis here by MultiRRomero:

http://stackoverflow.com/questions/5254838/calculating-distance-between-a-point-and-a-rectangular-box-nearest-point

Advertisements