in reply to Random hash element (low memory edition).

You can adapt the code from perlfaq5 (and, like it says, the Camel book) How do I select a random line from a file? for when iterating through your hash, once, instead of through the lines of a file.
my $chosen; my $n = 0; while(my($k, $v) = each %hash) { rand(++$n) < 1 and $chosen = $v; } return $chosen;

Replies are listed 'Best First'.
Re^2: Random hash element (low memory edition).
by BrowserUk (Patriarch) on Jan 27, 2008 at 14:30 UTC
      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; } } }
      }