Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Get random element from HoA

by Prof Vince (Friar)
on Dec 28, 2007 at 13:52 UTC ( #659331=note: print w/ replies, xml ) Need Help??


in reply to Get random element from HoA

Be aware that Fletch's solution doesn't give you an uniform distribution over the array elements if all the arrays don't have the same length. If you prefer that, you can use this :

my $count = do { # or keep track of it yourself while adding your elem +ents to %hoa use List::Util qw/sum/; sum map ~~@$_, values %hoa; }; sub randelt { my $i = int rand $count; my $v; while ((undef, $v) = each %hoa) { last if $i < @$v; $i -= @$v; } keys %hoa; # reset hash iterator $v->[$i]; };


Comment on Re: Get random element from HoA
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://659331]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2014-07-30 21:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (241 votes), past polls