How to transfer two arrays exactly the same in Perl?

Does anyone know how to randomly shuffle two arrays in exactly the same way in Perl? For example, let's say I have these two arrays:

Before shuffling: array 1: 1, 2, 3, 4, 5 array 2: a, b, c, d, e

After shuffling: array 1: 2, 4, 5, 3, 1 array 2: b, d, e, c, a

Thus, each element in each array is tied to its equivalent element.

+5
source share
4 answers

Try (something like this):

use List::Util qw(shuffle);
my @list1 = qw(a b c d e);
my @list2 = qw(f g h i j);
my @order = shuffle 0..$#list1;
print @list1[@order];
print @list2[@order];
+22
source

First: parallel arrays are a potential sign of bad code; you should see if you can use an array of objects or hashes and save yourself from this problem.

:

use List::Util qw(shuffle);

sub shuffle_together {
  my (@arrays) = @_;

  my $length = @{ $arrays[0] };

  for my $array (@arrays) {
    die "Arrays weren't all the same length" if @$array != $length;
  }

  my @shuffle_order = shuffle (0 .. $length - 1);

  return map {
    [ @{$_}[@shuffle_order] ]
  } @arrays;
}

my ($numbers, $letters) = shuffle_together [1,2,3,4,5], ['a','b','c','d','e'];

, shuffle , .

+9

List:: Util shuffle, .

use strict;
use warnings;

use List::Util qw(shuffle);

my @array1 = qw( a b c d e );
my @array2 = 1..5;

my @indexes = shuffle 0..$#array1;
my @shuffle1 = map $array1[$_], @indexes;
my @shuffle2 = map $array2[$_], @indexes;

Chris Jester-Young. - , .

+6

:

use strict;
use warnings;

use List::AllUtils qw(pairwise shuffle);

my @list1 = qw(a b c d e);
my @list2 = qw(f g h i j);

my @shuffled_pairs = shuffle pairwise{[$a, $b]} @list1, @list2;

for my $pair ( @shuffled_pairs ) {
    print "$pair->[0]\t$pair->[1]\n";
}

:

C:\Temp> sfl
e       j
b       g
d       i
a       f
c       h

, @shuffled_pairs C.

+6

All Articles