Selecting a random key from a hash

后端 未结 3 1866
萌比男神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
    

提交回复
热议问题