# 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) }

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

# Determine if two rectangles intersect without case logic

Assuming you have two rectangles A and B that exist parallel to the x and y axis and are defined by their upper left (x1,x2) and lower right corners (x2,y2). How can you calculate if A and B intersect without using case logic?

A = { (x1,y1), (x2,y2) }
B = { (x1,y1), (x2,y2) }

if (A.x1 < B.x2 &&
A.x2 > B.x1 &&
A.y1 < B.y2 &&
A.y2 > B.y1) {
then A and B intersect
}


There is a great analysis here:

http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other

And an awesome interactive visualization by Matthew Crumley here:

https://silentmatt.com/rectangle-intersection/