Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
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]; };

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 drinking their drinks and smoking their pipes about the Monastery: (1)
As of 2016-07-26 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What is your favorite alternate name for a (specific) keyboard key?


















    Results (231 votes). Check out past polls.