有人知道如何在Perl中以完全相同的方式随机排列两个数组吗?例如,假设我有这两个数组:
混洗前:数组1: 1,2,3,4,5数组2: a,b,c,d,e
混洗后:数组1: 2,4,5,3,1数组2: b,d,e,c,a
因此,每个数组中的每个元素都绑定到其等效元素。
发布于 2009-08-19 00:17:25
试试(像这样):
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];发布于 2009-08-19 00:22:07
首先:并行数组是错误代码的潜在标志;您应该看看是否可以使用对象或散列的数组,这样可以省去这些麻烦。
尽管如此:
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以随机顺序生成索引列表,然后对具有相同索引列表的所有数组进行切片。
发布于 2009-08-19 00:16:52
使用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的解决方案。Array slices是我应该想到的更好的选择。
https://stackoverflow.com/questions/1297224
复制相似问题