Selecting a random key from a hash

后端 未结 3 1857
萌比男神i
萌比男神i 2021-02-19 03:43

How do you select a random hash key? For my Flash+Perl card game I\'m trying to pick a random card from a hash where keys are: \"6 spades\", \"6 clubs\", etc. like this:

相关标签:
3条回答
  • 2021-02-19 04:11

    Get random value from %hash


    1. Store the keys of your %hash in @hash_keys.
    2. generate a random number between 0 and the length of @hash_keys
    3. get the random entry from @hash_keys
    4. use the acquired key to get your random value from %hash

    Example snippet:

    my %hash = ( 
      'stack' => 'overflow',
      'face'  => 'book',
      'inter' => 'net'
    );
    

    ## ALTERNATIVE 1 ##
    my @hash_keys    = keys %hash;
    
    my $random_key   = $hash_keys[rand @hash_keys];
    my $random_value = $hash{$random_key};
    

    ## ALTERNATIVE 2 ##
    my $random_val_2 = (%hash)[1+2*int rand keys%hash]; # TIMTOWTDI
    

    ## ALTERNATIVE 3 ##
    my $random_val_3 = [@_=%hash]->[1|rand@_];          # TIMTOWTDI
    
    0 讨论(0)
  • 2021-02-19 04:23

    Here's another way (demonstrating how to pick a random element from a list of unknown length):

    my $cards;
    my $chosen;
    while ( my $card = each %{$user->{HAND}} ) {
        $chosen = $card if rand(++$cards) < 1;
    }
    
    0 讨论(0)
  • 2021-02-19 04:25

    Somewhat more concise:

    my $random_value = $hash{(keys %hash)[rand keys %hash]};
    
    0 讨论(0)
提交回复
热议问题