Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
good chemistry is complicated,
and a little bit messy -LW
 
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 musing on the Monastery: (6)
As of 2014-04-18 06:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (462 votes), past polls