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
";
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…