Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Pulling random elements from hash

by sgifford (Prior)
on Jun 22, 2003 at 01:45 UTC ( [id://267896]=note: print w/replies, xml ) Need Help??


in reply to Pulling random elements from hash

You'd probably be better served by an array for this, where you could just do:
$array[int(rand(scalar(@array)))];
to choose a random element.

You can do much the same thing, though, by pulling the hash keys into a list and choosing one randomly:

$hk = (keys %hash)[int(rand(scalar(keys %hash)))]; $hv = $hash{$hk};
If you'll do it often, pull the keys into an array and just use that:
@arr = keys %hash; $hk = $arr[int(rand(scalar(@arr)))]; $hv = $hash{$hk};

With both of the hash solutions, you end up with two copies of all the keys, so it's less memory-efficient than an array, but probably fine if you have a few thousand entries or less.

Replies are listed 'Best First'.
Re^2: Pulling random elements from hash
by Aristotle (Chancellor) on Jun 22, 2003 at 02:00 UTC
    $array[int(rand(scalar(@array)))];
    Of course you can just write
    $array[rand @array];
    which will do exactly the same thing and is a bit less distracting to read.

    Makeshifts last the longest.

      I saw that in another post. Do you know why this is? It seems like rand is unlikely to pick an integer, and $array[3.14159] seems nonsensical, but I tried it and it works...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 19:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found