Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

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?

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2015-11-28 07:52 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (739 votes), past polls