Instead of a hash, you may want to use a data structure that maintains an order. An alist (a concept borrowed from lisp) seems suitable...

my @alist = ( [1 => 'cat'], [3 => 'mouse'], [5 => 'whale'], ); alistinsert(\@alist, 2, 'porcupine'); my $pair = alistatleast(\@alist, 4); # $pair now contains [5, 'whale'] print "The first element of the alist with a key of at least 4 is ($ +$pair[0], $$pair[1])\n"; sub alistatleast { my ($alist, $minval) = @_; for (@$alist) { return $_ if $$_[0] >= $minval; } } sub alistinsert { my ($alist, $car, $cdr) = @_; my $posn = 0; for (@$alist) { ++$posn if $$_[0] < $car } splice @$alist, $posn, 0, [$car, $cdr]; }

This saves you from doing a sort for every lookup, which will help performance if you have a lot of elements, taking a worst-case lookup down to O(n) time (from at least O(n log n) time if not more with the sort). It is possible to do better, by making the search binary instead of linear, which should get you down to O(log n) time I think. If your lookups have to be faster than that, you have to take drasting measures that will cost in other areas. e.g., you could have all possible keys be defined, or all keys that are multiples of some value, but if they don't have their own value give them a reference to the next one up with a real value. That gets you down to O(1) time for lookups, but it costs elsewise, by raising storage requirements and greatly complicating your code, among other things.


$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

In reply to Re: retrieve next avaiable element in sorted hash by jonadab
in thread retrieve next avaiable element in sorted hash by vinforget

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.