Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Random hash element (low memory edition).

by Roy Johnson (Monsignor)
on Jan 24, 2008 at 19:29 UTC ( [id://664125]=note: print w/replies, xml ) Need Help??


in reply to Random hash element (low memory edition).

You can find the number of elements using keys in a scalar context, and it won't take time or space to go through the elements.

But you could use the recipe for printing a random line from a file to just iterate through the hash without knowing how many elements it has and select a random one.

Yes, as long as you don't change the hash, keys will return keys in the same order every time. values will return values in the corresponding order.


Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Random hash element (low memory edition).
by amarquis (Curate) on Jan 24, 2008 at 20:51 UTC

    That method is awfully neat, but my perl skills are not so I'll hit you with a follow-up question.

    rand($.) < 1 && ($line = $_) while <>;

    So this iterates through the file and, if a random number from 0 to the current line number is less than 1, selects the current line, overwriting previous choices? So, in my case, I'd just keep a count variable for how many elements I've been through and use that in place of $.?

    I'm going to have to check out the proof of that, it is really interesting that everything evens out (i.e. the first elements have a high chance of being overwritten, the latter elements have a high chance of just not being picked, and it all balances out to a random selection.) Thanks for pointing me to that FAQ entry!

      So, in my case, I'd just keep a count variable for how many elements I've been through and use that in place of $.?

      Exactly.


      Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-24 19:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found