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

Re: Randomly reassign hash keys

by thanos1983 (Parson)
on Apr 26, 2017 at 18:02 UTC ( [id://1188988]=note: print w/replies, xml ) Need Help??


in reply to Randomly reassign hash keys

Hello cormanaz,

Another approach could be:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash = ( "a" => 1, "b" => 2, "c" => 3, "d" => 4 ); # Export keys from the hash my @keys = keys %hash; # Export values from the hash my @values = values %hash; my %new_hash; for ( 0 .. $#keys ) { $new_hash{splice @keys, rand @keys, 1} = splice @values, rand @val +ues, 1; } print Dumper \%new_hash; __DATA__ $ perl test.pl $VAR1 = { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 };

Update:in case that someone is interested in speed simple foreach element loop is always faster. Sample of code:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Benchmark::Forking qw( cmpthese ); my %hash = ( "a" => 1, "b" => 2, "c" => 3, "d" => 4 ); # Export keys from the hash my @keys = keys %hash; # Export values from the hash my @values = values %hash; my %new_hash_1; my %new_hash_2; cmpthese(100000000, { 'loop indices' => sub { for ( 0 .. $#keys ) { $new_hash_1{splice @keys, rand @keys, 1} = splice @values, ran +d @values, 1; } }, 'loop elements' => sub { for ( @keys ) { $new_hash_2{splice @keys, rand @keys, 1} = splice @values, ran +d @values, 1; } }, }); __DATA__ $ perl test.pl Rate loop indices loop elements loop indices 5211047/s -- -58% loop elements 12531328/s 140%

Hope this helps.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found