我怎样才能生成在Perl数组的所有排列?数组、排列、Perl

2023-09-11 01:46:17 作者:执着

什么是最好的(高雅,简洁,高效)的方式来产生所有 N!在Perl中的数组?

的排列

例如,如果我有一个数组 @arr =(0,1,2),我要输出所有排列:

  0 2 1
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
 

这也许应该是一个函数,该函数返回一个迭代器(懒惰/延迟评价,因为 N 可以变得如此不可能大),所以它可以被称为是这样的:

 我@arr =(0,1,2);
我的$ ITER = getPermIter(@arr);
而(我@perm = $ iter->接下来()){
    打印@perm \ N的;
}
 
C语言,对任意长度的数组进行冒泡排序,我的代码哪里有问题 为什么我输入数组第一个元素,第一个数会没

解决方案

请参阅 perlfaq4 :的我怎样重排列表中的N个元素

What's the best (elegant, simple, efficient) way to generate all n! permutations of an array in perl?

For example, if I have an array @arr = (0, 1, 2), I want to output all permutations:

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0

It should probably be a function that returns an iterator (lazy/delayed evaluation because n! can become so impossibly large), so it can be called like this:

my @arr = (0, 1, 2);
my $iter = getPermIter(@arr);
while (my @perm = $iter->next() ){
    print "@perm\n";
}

解决方案

See perlfaq4: "How do I permute N elements of a list?"