A sub to detect overlap of two rectangles is not that hard, especially if you go the other way: eliminate all the possibilities on how not to overlap. The rectangles will not overlap if one is completely to the left of the other, or vice vera, nor if it's completely below the other, or vice versa. In any other circumstances, they must overlap. This code will do that. I do allow the rectangles to touch.
use List::Util qw(min max);
sub rect_overlap {
my($r1, $r2) = @_; # two rectangles, like [x1, y1, x2, y2]
# r1 is on the left of r2
return 0 if max(@$r1[0, 2]) <= min(@$r2[0, 2]);
# r2 is on the left of r1
return 0 if max(@$r2[0, 2]) <= min(@$r1[0, 2]);
# r1 is below r2
return 0 if max(@$r1[1, 3]) <= min(@$r2[1, 3]);
# r2 is below r1
return 0 if max(@$r2[1, 3]) <= min(@$r1[1, 3]);
# they must overlap:
return 1;
}
# some tests:
use Test::Simple 'no_plan';
ok rect_overlap [10, 10, 30, 30], [20, 20, 40, 60]; # do
ok !rect_overlap [10, 10, 30, 30], [20, 40, 40, 60]; # don't
ok rect_overlap [10, 10, 30, 30], [15, 15, 20, 20]; # inside
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.