I've seen many algorithms to intersect two arrays but none to find the intersect of two ranges of real numbers. For instance if I had the ranges 1-5 and 2-6, I needed to calculate that the intersect range was 3 long. (note that the strict intersect was 2-5 but I just need to know the length of this interval). After thinking about the problem for a little while I came up with this mathematically oriented solution:

sub intersect { my ($a,$b,$c,$d) = @_; my ($n1,$n2) = ([$a,$b],[$c,$d]); if($a > $c){ my $t = $n1; $n1 = $n2; $n2 = $t; } ($a,$b,$c,$d) = (@n1,@n2); return ($b-$c)*($b>$c)-($b-$d)*($b>$d); }

which I later compressed into this 2-line obfuscation:

sub intersect3 { my ($a,$b,$c,$d) = map {($_->[0],$_->[1])} sort { $a->[0] <=> $b-> +[0] } ([@_[0,1]],[@_[2,3]]); return ($b-$c)*($b>$c)-($b-$d)*($b>$d); }

I kept looking for a more elegant/shorter/cooler way to do this but have gotten no farther after many hours of meditation. I wonder if some of the more enlightened among us can offer further ideas?

-caedes


In reply to Finding the intersect of two ranges by caedes

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.