# 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/
{"ft_lang_label":"__label__en","ft_lang_prob":0.7949496,"math_prob":0.99285126,"size":1130,"snap":"2019-51-2020-05","text_gpt3_token_len":342,"char_repetition_ratio":0.092362344,"word_repetition_ratio":0.06285714,"special_character_ratio":0.31946903,"punctuation_ratio":0.1870229,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9990522,"pos_list":[0,1,2],"im_url_duplicate_count":[null,4,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-19T08:30:23Z\",\"WARC-Record-ID\":\"<urn:uuid:6af3c422-45e9-4573-b468-a0735f5ba883>\",\"Content-Length\":\"121301\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:da1830f7-1783-43e3-8b2d-1070026d527b>\",\"WARC-Concurrent-To\":\"<urn:uuid:8c8bd082-02de-42d8-8e18-0ce9d0e3248b>\",\"WARC-IP-Address\":\"192.0.78.13\",\"WARC-Target-URI\":\"https://memext.wordpress.com/tag/rectangle/\",\"WARC-Payload-Digest\":\"sha1:37XSATGIQHSNHSLW4JEAZRRJ5YITVJHJ\",\"WARC-Block-Digest\":\"sha1:OXD2LLM47HCVS37E26C4YPAWGE4F7TPQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579250594333.5_warc_CC-MAIN-20200119064802-20200119092802-00106.warc.gz\"}"}