Permutations: Difference between revisions

Content added Content deleted
(→‎{{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, append/2, delete/2, map/2]).
-import(lists, [append/1, map/2, seq/2, split/2]).


%% insert element E into list L immediately after the item at position N
permute([]) ->
%% (N=0 prepends E to the list)
[[]];
permute(L) ->
insert( L, N, E ) ->
{H, T} = split( N, L ),
append(map(fun(X) ->
append( [H, [E], T] ).
map(fun(P) -> append([X],P) end, permute(delete(X, L)))

end, L)).</lang>
% Return a list of all the permutations of the given list
permute( [] ) -> [[]];
permute( [H|T] ) ->
append( map( fun(P) ->
map( fun(N) ->
insert(P, N, H)
end,
seq( 0, length(P) ))
end,
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