Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Randomly reassign hash keys

by poj (Monsignor)
on Apr 26, 2017 at 17:07 UTC ( #1188984=note: print w/replies, xml ) Need Help??


in reply to Randomly reassign hash keys

@hash{ keys %hash } = shuffle values %hash;

update : you said 'random' so that means it could result in no change.

poj

Replies are listed 'Best First'.
Re^2: Randomly reassign hash keys
by Anonymous Monk on Apr 26, 2017 at 18:20 UTC

    And, if you do that a lot, there's this alternative for your consideration:

    sub inplace_shuffle { @_[keys @_] = shuffle @_ } inplace_shuffle (values %foo);

      The functionality of keys operating on an array to return the indices of the array (see similarily values, each) was added with Perl version 5.12. The following will work with any Perl 5 version:
          sub inplace_shuffle { @_[ 0 .. $#_ ] = shuffle @_ }


      Give a man a fish:  <%-{-{-{-<

Re^2: Randomly reassign hash keys
by Eily (Prior) on Apr 26, 2017 at 17:20 UTC

      Just a random funny observation having done it myself a few times, taking a fully comprehensive "slice" of a hash like this sounds linguistically silly to me even though it's perfectly valid in the Perl language. Hmm... which is the better analogy? Is it like cutting a personal pizza in to slices and then proceeding to eat them all in one sitting, or more like just folding your one slice (the entire pizza) up like a calzone to eat it? After all, in the latter case you don't even need to get your pizza cutter dirty, that's just efficiency in practice. :-)

      I wonder if there is a word in the English language for when a word that's technically correct is also simultaneously nonsensical, like here with the "slice" in fact being "the entire thing". Oxymoron or misnomer don't seem quite right, because strictly speaking there aren't any contradictory terms involved and "slice" is still the correct name. Are there any logophile Monks with suggestions? (I cross posted on Stack Exchange since it's admittedly a bit off topic here)

      Just another Perl hooker - Working on the corner... corner conditions that is.
        There's nothing nonsensical about it. The largest subset is always equal to the full set.
Re^2: Randomly reassign hash keys
by jdporter (Canon) on Apr 28, 2017 at 02:14 UTC
    use List::Util qw(shuffle); use List::MoreUtils qw(zip); %hash = zip @{[shuffle keys %hash]}, @{[values %hash]};

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1188984]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2018-06-18 11:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?



    Results (109 votes). Check out past polls.

    Notices?