Permutations: Difference between revisions
Content added Content deleted
(→{{header|Factor}}: Add Erlang) |
(→{{header|Erlang}}: Replace algorithm with more efficient one.) |
||
Line 608: | Line 608: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<lang Erlang>module(permute). |
<lang Erlang>-module(permute). |
||
-export([permute/1]). |
-export([permute/1]). |
||
-import(lists, [append/1, |
-import(lists, [append/1, map/2, seq/2, split/2]). |
||
%% insert element E into list L immediately after the item at position N |
|||
⚫ | |||
%% (N=0 prepends E to the list) |
|||
[[]]; |
|||
insert( L, N, E ) -> |
|||
{H, T} = split( N, L ), |
|||
⚫ | |||
append( [H, [E], T] ). |
|||
map(fun(P) -> append([X],P) end, permute(delete(X, L))) |
|||
⚫ | |||
% Return a list of all the permutations of the given list |
|||
permute( [] ) -> [[]]; |
|||
⚫ | |||
⚫ | |||
map( fun(N) -> |
|||
insert(P, N, H) |
|||
end, |
|||
seq( 0, length(P) )) |
|||
⚫ | |||
permute( T ))). |
|||
</lang> |
|||
Demonstration (escript): |
Demonstration (escript): |
||
Line 626: | Line 637: | ||
<pre>[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]</pre> |
<pre>[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]</pre> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
The all-permutations word is part of factor's standard library. See http://docs.factorcode.org/content/word-all-permutations,math.combinatorics.html |
The all-permutations word is part of factor's standard library. See http://docs.factorcode.org/content/word-all-permutations,math.combinatorics.html |