The advantage? I'm not sure there is one. It is a different approach than the one proposed by you in Re: Random hash element (low memory edition)., and it is not worse. That is interesting by itself.

It could even be beneficial in case of a tied hash, as a call to keys makes it loop through all the keys of the tied hash, just to get the count. So, in that case, your code will loop through them at least once, to get the keys, and a fraction of a cycle (up to a complete cycle) more than that. I assume that my approach could be faster, in that case.

But note that the Big O is still the same for both approaches: O(n), where n is the number of hash keys.

It might become more interesting if one wants a weighted probability, then in my code, you "just" have to replace the test condition by a different function of rand() and a weight that depends on the current key. But the structure of the code can remain the same. That's a huge advantage.

I have derived a usable function in a journal entry on use.perl.org.

With weighted probabilities (the weight is a positive number that is proportional to the desired odds that this item is picked; if it's zero, the item is skipped), the code can be:

my($threshold, $value); while(my($k, $v) = each(%hash)) { if(my $weight = weight($k)) { # function call my $rand = -log(1 - rand)/$weight; if(not defined $threshold or $rand < $threshold) { $threshold = $rand; $value = $v; } } }
}

In reply to Re^3: Random hash element (low memory edition). by bart
in thread Random hash element (low memory edition). by amarquis

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.