我正在尝试使用 Math::Combinatorics 生成数组的唯一排列。如CPAN page说可以使用 next_string() 来完成:
use Math::Combinatorics;
my @arr = [1,1,1,0,0];
$c = Math::Combinatorics->new( count=>5, data=>[\@arr], frequency=>[3,2] );
while (@permu = $c->next_string()){
print "@permu\n";
}
但是这段代码给了我以下错误:必须使用未传递给构造函数的“频率”参数的 next_permutation,我不明白为什么。
最佳答案
你的程序有很多问题。您的数据类型不匹配。
如果您想使用频率
,则只需指定唯一元素一次,但指定它们出现的次数。您为频率提供的数组引用必须与数据数组的长度相同:
use Math::Combinatorics;
my @array = (1,0); # an array, not an array reference
$c = Math::Combinatorics->new(
count => 5,
data => \@array, # now you take a reference
frequency => [3,2]
);
while (@permu = $c->next_string ){
print "@permu\n";
}
现在你应该得到你想要的输出,这些是不同的组合,你无法区分多个 1 和多个 0 之间的区别:
0 1 1 1 0
0 1 1 0 1
0 1 0 1 1
0 0 1 1 1
1 0 1 1 0
1 0 1 0 1
1 0 0 1 1
1 1 0 1 0
1 1 0 0 1
1 1 1 0 0
如果您不使用频率
,则只需指定数据数组中的所有元素即可。但是,您可能会避免这种情况,因为它将每个元素视为不同的元素,因此不会折叠看起来相同的组合。
关于perl - 为什么 Perl 的 Math::Combinatorics 提示 "must use next_permutation of ' 频率'参数未传递给构造函数”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741340/