If the values in @F are very sparse, you should probably use a hash to make the reverse map instead of the array @G. If you had a case where @F = qw/1 3 5 1000000 2000000/;, you wouldn't want to reverse map that into an array, which would become 2 million elements large. Apart from that, it's just plain easier to write a reverse map into a hash: @G{@F} = ();

It's not clear to me from your description, but is the thing you really want the set intersection of the set @F with 25..35 and with 50..75? If this is the case, maybe one of the Set:: or Array:: modules might be worth inspecting (Set::IntRange?). Although I'm not familiar with what's out there, I would assume there would be some modules out there highly optimized for the intersection operation.

If you're not looking for a set intersection, I don't see any obvious optimizations here, other than the possible sparseness of the reverse map that I mentioned.

Update: I noticed your code always returns a range, even if some of the intermediaries in the range aren't in @F. thinker gives a very nice algorithm for set intersection with a range, but if you need to always return a range (even including elements not in @F), here's an adaptation:

sub range{ my($lo, $hi) = @_; ($lo, $hi) = (sort grep {$_ >= $lo and $_ <= $hi} @F)[0,-1]; return $lo..$hi; }
Depending on the data, this might be better than your original code. While this has to process your entire set of values, if the values are extremely sparse, you may end up ++'ing $lo and --'ing $hi all day in your algorithm.

blokhead


In reply to Re: mapping lists by blokhead
in thread mapping lists by belg4mit

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.