sean
sean

Reputation: 57

arrange array order to match shuffled array

I'm having a big headache here. I want to shuffle an array of positions and then shuffle another array using the same pattern:

use warnings;
use List::Util 'shuffle';

my @order = qw/1 3 2 0/;
my @words = qw/test this a is/; 
@new_order = shuffle(@order);
#some code.... ?
print @words; #this is a test

Result:

randomized words: this a is test.
randomized Order: 0 2 1 3.
sort: this is a test.

next run

randomized words: test a this is.
randomized Order:  2 3 1 0.
sort: this is a test.

and so on...

i have tried and searched but to be honest im just utterly puzzled :/

Upvotes: 0

Views: 82

Answers (2)

ysth
ysth

Reputation: 98388

If all you want is to shuffle two arrays using the same pattern, do:

use warnings;
use List::Util 'shuffle';

my @order = qw/1 3 2 0/;
my @words = qw/test this a is/;

my @shuffle = shuffle(0..$#order);
my @new_order = @order[@shuffle];
my @new_words = @words[@shuffle];

If it is something more complicated, it would really help to see the code that generates your sample output (after the shuffling part that you are asking for help with).

Upvotes: 1

Borodin
Borodin

Reputation: 126722

The simplest solution just provides the some code.... ? comment in your own program. But the call to shuffle is superfluous, and it works only because you have presumably chosen your numbers that way

use strict;
use warnings;

use List::Util 'shuffle';

my @order = qw/ 1 3 2 0 /;
my @words = qw/ test this a is /; 

my @new_order = shuffle(@order);

@words = @words[@order];
print "@words\n";

output

this is a test

Upvotes: 0

Related Questions