Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
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 about the Monastery: (7)
As of 2014-09-17 04:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (57 votes), past polls