Permutations: Difference between revisions

→‎{{header|Perl}}: Clean up perl4-ish code, and add modules
(jq)
(→‎{{header|Perl}}: Clean up perl4-ish code, and add modules)
Line 2,494:
 
=={{header|Perl}}==
There are many modules that can do permutations, or it can be fairly easily done by hand with an example below. In performance order for simple permutation of 10 scalars, a sampling of some solutions:
<lang perl6># quick and dirty recursion
- 1.7s [https://metacpan.org/pod/Algorithm::FastPermute Algorithm::FastPermute] permute iterator
sub permutation(){
- 1.7s [https://metacpan.org/pod/Algorithm::Permute Algorithm::Permute] permute iterator
- 2.0s [https://metacpan.org/pod/ntheory ntheory] forperm iterator
- 6.3s [https://metacpan.org/pod/Algorithm::Combinatorics Algorithm::Combinatorics] permutations iterator
- 9.1s the recursive sub below
- 21.1s [https://metacpan.org/pod/Math::Combinatorics Math::Combinatorics] permutations iterator
 
Example:
{{libheader|ntheory}}
<lang perl>use ntheory qw/forperm/;
my @tasks = (qw/party sleep study/);
forperm {
print "@tasks[@_]\n";
} scalar(@tasks);</lang>
{{out}}
<pre>
party sleep study
party study sleep
sleep party study
sleep study party
study party sleep
study sleep party
</pre>
 
A simple recursive routine:
<lang perl>sub permutation() {
my ($perm,@set) = @_;
print "$perm\n" || return unless (@set);
&permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0..$#set);
}
my @input = (qw/a, 2, c, 4)/;
&permutation('',@input);</lang>
{{out}}
<pre>
Anonymous user