Domanda

Qualcuno sa come mischiare due array casuale esattamente nello stesso modo in Perl? Ad esempio, dire che ho questi due array:

Prima di rimescolamento: matrice 1: 1, 2, 3, 4, 5 matrice 2: a, b, c, d, e

Dopo aver mescolato: matrice 1: 2, 4, 5, 3, 1 matrice 2: b, d, e, c, un

Così ogni elemento in ogni matrice è legato al suo elemento equivalente.

È stato utile?

Soluzione

Prova (qualcosa di simile) in questo modo:

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

Altri suggerimenti

Per prima cosa: file parallele sono un potenziale segno di codice cattivo; si dovrebbe vedere se è possibile utilizzare un array di oggetti o hash e risparmiare quel guaio.

Tuttavia:

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

Fondamentalmente, utilizzare shuffle per produrre un elenco di indici in ordine casuale, e poi tagliare tutte le matrici con la stessa lista di indici.

List :: Util shuffle per mescolare un elenco di indici e la mappa risultati sulle matrici.

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;

Aggiorna Usare la soluzione di Chris Jester-Young. sono una scelta migliore che ho dovuto pensarci .

Ecco un altro modo:

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";
}

Output:

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

In questo modo, è possibile scorrere direttamente sopra @shuffled_pairs senza bisogno di mantenere una matrice in più per gli indici ed evitare loop C-stile.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top