All,
Intrepid asked in the CB for a piece of code that would satisfy the following requirements:

These have been generalized a bit as hashref keys were involved, but I provided the following straightforward solution:

my @min_keys = sort { length($a) <=> length($b) || $a cmp $b } keys %$ +hashref; my $min = length $min_keys[0]; for ( 1 .. $#min_keys ) { if ( length $min_keys[$_] != $min ) { splice @min_keys, $_; last; } } # maxstr & random print join "\t", $min_keys[-1], $min_keys[ rand @min_keys ];
There was a follow on discussion about how this could be done efficiently. While some were interested in a general solution that may be incorporated into List::Util, I felt a variation of the watermark algorithm was all that was needed to satisfy all the requirements in a single pass:
my @list = qw(zero one two three four five six seven eight nine ten el +even twelve); my ($maxstr, $random) = find_shortest( @list ); print join "\t", $maxstr, $random; sub find_shortest { my ($pos, $len, $maxstr, @min) = (0, undef, '', 0, undef); my %dispatch = ( -1 => sub { ($len, $pos) = (length($_), 0); ($min[$pos], $maxstr) = ($_, $_); }, 0 => sub { $min[++$pos] = $_; $maxstr = $_ if $_ gt $maxstr; }, 1 => sub { return }, ); for ( @_ ) { if ( ! defined $len ) { $len = length(); ($min[$pos], $maxstr) = ($_, $_); next; } $dispatch{ length($_) <=> $len }->(); } return ($maxstr, (@min[0..$pos])[rand $pos]); }

There are still ways to improve on it, but I thought it was neat and only required a minimal amount of extra effort. How could you improve (keeping the original 3 requirements in mind)?
Cheers - L~R


In reply to Efficiently finding values of an extremity by Limbic~Region

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.