Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How to randomly select a key whose value is between a range?

by stevieb (Canon)
on Sep 05, 2015 at 00:59 UTC ( [id://1141094]=note: print w/replies, xml ) Need Help??


in reply to How to randomly select a key whose value is between a range?

Hash keys are never guaranteed to be in order, so selecting based on a number will not work to get you your middle keys.

If your keys are really all single letters, this will work (note that you'll have to either stringify the values or do hex work on them if they are indeed hex):

#!/usr/bin/perl use warnings; use strict; my %hash = ( a => 00, b => 01, c => 02, d => 03, e => 04, f => 05, g => 06 ); my @keys = ('c'..'f'); print $hash{$keys[int(rand(@keys))]} . "\n";

However, I doubt this is your real info. Can you supply us with real data if this isn't it? If your hash isn't exactly what you've shown here, the answers you are provided with are unlikely to work with a hash with keys that are not a single letter, or values that are not sequential.

Replies are listed 'Best First'.
Re^2: How to randomly select a key whose value is between a range?
by sundialsvc4 (Abbot) on Sep 05, 2015 at 13:58 UTC

    ... and notice how golux neatly side-stepped that issue in his (excellent) post #1:   the relevant range of keys was extracted (using grep as a clever alternative to a loop, to iterate through the entire set of key returned by keys), and placed into an array, which of course uses a zero-based numeric index.   The keys were selected from this array.   As long as you determine that the list contains at least one key, this approach always works.

    If you need to randomly select more than one key within the range, such that the same key will never be selected twice, a good way to do so is:   select the array of keys (as shown), then shuffle the array, then draw from the top.   Array::Shuffle and Algorithm::Numerical::Shuffle both illustrate how to do this.   (Fair warning:   read the fine-print in delete with regard to arrays, if you’re considering other ways to do this.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-26 00:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found