Permutations: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl}}: cleaned up)
Line 4,572: Line 4,572:


=={{header|Perl}}==
=={{header|Perl}}==
A simple recursive implementation.
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 perl>sub permutation {
- 1.7s [https://metacpan.org/pod/Algorithm::FastPermute Algorithm::FastPermute] permute iterator
my ($perm,@set) = @_;
- 1.7s [https://metacpan.org/pod/Algorithm::Permute Algorithm::Permute] permute iterator
print "$perm\n" || return unless (@set);
- 2.0s [https://metacpan.org/pod/ntheory ntheory] forperm iterator
permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0..$#set);
- 6.3s [https://metacpan.org/pod/Algorithm::Combinatorics Algorithm::Combinatorics] permutations iterator
}
- 9.1s the recursive sub below
my @input = (qw/a b c d/);
- 21.1s [https://metacpan.org/pod/Math::Combinatorics Math::Combinatorics] permutations iterator
permutation('',@input);</lang>
{{out}}
<pre>abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba</pre>


For better performance, use a module like <code>ntheory</code> or <code>Algorithm::Permute</code>.
Example:
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use ntheory qw/forperm/;
<lang perl>use ntheory qw/forperm/;
Line 4,586: Line 4,612:
forperm {
forperm {
print "@tasks[@_]\n";
print "@tasks[@_]\n";
} scalar(@tasks);</lang>
} @tasks;</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,595: Line 4,621:
study party sleep
study party sleep
study sleep party
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>
a2c4
a24c
ac24
ac42
a42c
a4c2
2ac4
2a4c
2ca4
2c4a
24ac
24ca
ca24
ca42
c2a4
c24a
c4a2
c42a
4a2c
4ac2
42ac
42ca
4ca2
4c2a
</pre>
</pre>