我怎样才能生成在Perl数组的所有排列? [英] How can I generate all permutations of an array in Perl?

查看:218
本文介绍了我怎样才能生成在Perl数组的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的(高雅,简洁,高效)的方式来产生所有 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的;
}
 

解决方案

请参阅 perlfaq4 :的我怎样重排列表中的N个元素<​​/A>

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?"

这篇关于我怎样才能生成在Perl数组的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆