Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shuffle two arrays in exactly the same way in Perl?

Does anyone know how to shuffle two arrays randomly in exactly the same way in Perl? For example, 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

So every element in each array is bound to its equivalent element.

like image 927
Abdel Avatar asked Aug 19 '09 00:08

Abdel


People also ask

How do I randomize an array in Perl?

Use the shuffle function from the standard List::Util module, which returns the elements of its input list in a random order.

How to optimally shuffle array?

A simple solution is to create an auxiliary array temp[] which is initially a copy of arr[]. Randomly select an element from temp[], copy the randomly selected element to arr[0], and remove the selected element from temp[]. Repeat the same process n times and keep copying elements to arr[1], arr[2], … .

How to randomly shuffle an array in c++?

Shuffle an Array using STL in C++ STL contains two methods which can be used to get a shuffled array. These are namely shuffle() and random_shuffle(). This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator.


2 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];
like image 148
Chris Jester-Young Avatar answered Oct 15 '22 18:10

Chris Jester-Young


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 that trouble.

Nonetheless:

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'];

Basically, use shuffle to produce a list of indices in random order, and then slice all of the arrays with the same list of indices.

like image 36
hobbs Avatar answered Oct 15 '22 19:10

hobbs