We split the task into two parts: The first part is to represent permutations, to initialize them and to go from one permutation to another one, until the last one has been reached. This can be used elsewhere, e.g., for the Topswaps [[1]] task. The second part is to read the N from the command line, and to actually print all permutations over 1 .. N.

procedure Set_To_First(P: out Permutation; Is_Last: out Boolean)isbeginfor I in P'Rangeloop P (I) := I;endloop; Is_Last := P'Length = 1; -- if P has a single element, the fist permutation is the last oneend Set_To_First;

% Use zipper to pick up first element of permutationzipper([],_,Acc)->lists:reverse(Acc);zipper([H|T],R,Acc)->% place current member in front of all permutations% of rest of set - both sides of zipperprepend(H,permute(lists:reverse(R,T)),% pass zipper state for continuationT,[H|R],Acc).

Instead of looking up unused values, this program starts from [1, ..., n] and does only swaps, hence the array always represents a valid permutation.
The values need to be "swapped back" after the recursive call.

So far, we have conclusion from the above performance:
1) subnexper is the 3rd fast with ifort and the 2nd with gfortran.
2) generate is the slowest one with not only ifort but gfortran.
3) perm is the 2nd fast one with ifort and the 3rd one with gfortran.
4) nextp is the fastest one with both ifort and gfortran (the winner in this test).

Note: It is worth mentioning that the performance of this test is dependent not only on algorithm, but also on computer where the test runs. Therefore we should run the test on our own computer and make conclusion by ourselves.

GAP can handle permutations and groups. Here is a straightforward implementation : for each permutation p in S(n) (symmetric group),
compute the images of 1 .. n by p. As an alternative, List(SymmetricGroup(n)) would yield the permutations as GAP Permutation objects,
which would probably be more manageable in later computations.

%% permutationSet(List, Set) is true if List is a permutation of Set::- pred permutationSet(list(A)::out,set(A)::in) is nondet.

%% Two ways to compute all permutations of a given list (using backtracking)::- func all_permutations1(list(int))=set_ordlist.set_ordlist(list(int)).:- func all_permutations2(list(int))=set_ordlist.set_ordlist(list(int)).

This implementation merely prints out the orbit of the list (1, 2, ..., n) under the action of Sn. It shows off Modula-3's built-in Set type and uses the standard IntSeq library module.

MODULE Permutations EXPORTS Main;

IMPORT IO, IntSeq;

CONST n =3;

TYPE Domain =SETOF[1.. n ];

VAR

chosen: IntSeq.T; values := Domain {};

PROCEDURE GeneratePermutations(VAR chosen: IntSeq.T; remaining: Domain)=(* Recursively generates all the permutations of elements in the union of "chosen" and "values". Values in "chosen" have already been chosen; values in "remaining" can still be chosen. If "remaining" is empty, it prints the sequence and returns. Otherwise, it picks each element in "remaining", removes it, adds it to "chosen", recursively calls itself, then removes the last element of "chosen" and adds it back to "remaining".*)BEGINFOR i :=1TO n DO(* check if each element is in "remaining" *)IF i IN remaining THEN(* if so, remove from "remaining" and add to "chosen" *) remaining := remaining - Domain { i }; chosen.addhi(i);IF remaining # Domain {}THEN(* still something to process? do it *) GeneratePermutations(chosen, remaining);ELSE(* otherwise, print what we've chosen *)FOR j :=0TO chosen.size()-2DO IO.PutInt(chosen.get(j)); IO.Put(", ");END; IO.PutInt(chosen.gethi()); IO.PutChar('\n');END;(* add "i" back to "remaining" and remove from "chosen" *) remaining := remaining + Domain { i }; EVAL chosen.remhi();END;END;END GeneratePermutations;

This version works on any type, and requires the library's Set and Sequence. As usual in Modula-3, the generic instance will need to be instantiated for whatever type you want to use, and you will also need to instantiate a set of, sequence of, and sequence of sequences of the domain elements. This will have to be taken care of by the m3makefile.

interface

Suppose that D is the domain of elements to be permuted. This module requires a DomainSeq (Sequence of D), a DomainSet (Set of D), and a DomainSeqSeq (Sequence of Sequences of Domain).

(* "Domain" is where the things to permute come from (unused in interface). "DomainSeq" is a "Sequence" of "Domain". "DomainSet" is a "Set" of "Domain". "DomainSeqSeq" is a "Sequence" of "DomainSeq".*)

PROCEDURE GeneratePermutations(READONLY chosen: DomainSeq.T;READONLY remaining: DomainSet.T;READONLY result: DomainSeqSeq.T);(* Recursively generates all the permutations of elements in the union of "chosen" and "remaining". Values in "chosen" have already been chosen; values in "remaining" can still be chosen. If "remaining" is empty, it adds the permutation to "result". Otherwise, it picks each element in "remaining", removes it, adds it to "chosen", recursively calls itself, then removes the last element of "chosen" and adds it back to "remaining". Although the parameters are modified, we can describe them as "READONLY" because we do not re-assign them.*)

END GenericPermutations.

implementation

In addition to the interface's specifications, this requires a generic Domain. Some implementations of a set are not safe to iterate over while modifying (e.g., a tree), so this copies the values and iterates over them.

(* Recursively generates all the permutations of elements in the union of "chosen" and "remaining". Values in "chosen" have already been chosen; values in "remaining" can still be chosen. If "remaining" is empty, it adds the permutation to "result". Otherwise, it picks each element in "remaining", removes it, adds it to "chosen", recursively calls itself, then removes the last element of "chosen" and adds it back to "remaining".*)

(* if this is not the last remaining elements, call recursively *)IF remaining.size()#0THEN GeneratePermutations(chosen, remaining, result);ELSE(* we have a new permutation; add a copy to the set *)VAR newPerm :=NEW(DomainSeq.T).init(chosen.size());BEGINFOR i :=0TO chosen.size()-1DO newPerm.addhi(chosen.get(i));END; result.addhi(newPerm);END;END;

(* move r back from chosen *)EVAL remaining.insert(chosen.remhi());

END;

END GeneratePermutations;

BEGINEND GenericPermutations.

Sample Usage

Here the domain is Integer, but the interface doesn't require that, so we "merely" need IntSeq (a Sequence of Integer), IntSetTree (a set type I use, but you could use SetDef or SetList if you prefer; I've tested it and it works), IntSeqSeq (a Sequence of Sequences of Integer), and IntPermutations, which is GenericPermutations instantiated for Integer.

MODULE GPermutations EXPORTS Main;

IMPORT IO, IntSeq, IntSetTree, IntSeqSeq, IntPermutations;

CONST

n =7;

VAR

chosen: IntSeq.T; remaining: IntSetTree.T; result: IntSeqSeq.T;

PROCEDURE Factorial(n:CARDINAL):CARDINAL=VAR result :=1;BEGINFOR i :=2TO n DO result := result * i;END;RETURN result;END Factorial;

a little bit more speed.I take n = 12.
The above version takes more than 5 secs.My permlex takes 2.8s, but in the depth of my harddisk I found a version, creating all permutations using k places out of n.The cpu loves it! 1.33 s.
But you have to use the integers [1..n] directly or as Index to your data.
1 to n are in lexicographic order.

The distribution includes builtins\permute.e, which is reproduced below. This can be used to retrieve all possible permutations, in
no particular order. The elements can be any type. It is just as fast to generate the (n!)th permutation as the first, so some applications may benefit by storing
an integer key rather than duplicating all the elements of the given set.

The procedure nextPermutation() takes an array of integers as input and transforms its contents into the next lexicographic permutation of it's elements (i.e. integers). It returns #True if this is possible. It returns #False if there are no more lexicographic permutations left and arranges the elements into the lowest lexicographic permutation. It also returns #False if there is less than 2 elemetns to permute.

The integer elements could be the addresses of objects that are pointed at instead. In this case the addresses will be permuted without respect to what they are pointing to (i.e. strings, or structures) and the lexicographic order will be that of the addresses themselves.

The follwing functions start from a list [0 ... n-1] and exchange elements to always have a valid permutation. This is done recursively: first exchange a[0] with all the other elements, then a[1] with a[2] ... a[n-1], etc. thus yielding all permutations.

These two solutions make use of a generator, and "yield from" introduced in PEP-380. They are slightly different: the latter produces permutations in lexicographic order, because the "remaining" part of a (that is, a[i+1:]) is always sorted, whereas the former always reverses the exchange just after the recursive call.

On three elements, the difference can be seen on the last two permutations:

Given a permutation, one can easily compute the next permutation in some order, for example lexicographic order, here. Then to get all permutations, it's enough to start from [0, 1, ... n-1], and store the next permutation until [n-1, n-2, ... 0], which is the last in lexicographic order.

do k=1for x /*build a list of permutation symbols. */ _=p(word(uSyms,k) p(substr(@0abcS,k,1) k))/*get or generate a symbol.*/iflength(_)\==1then sep='_'/*if not 1st character, then use sep. */ $.k=_ /*append the character to symbol list. */end/*k*/

There is a built-in function in the Scala collections library, that is part of the language's standard library. The permutation function is available on any sequential collection. It could be used as follows given a list of numbers:

In practice there's no need to write this because it's in the standard library.

#import std

permutations =

~&itB^?a( # are both the input argument list and its tail non-empty? @ahPfatPRD *= refer ^C( # yes, recursively generate all permutations of the tail, and for each one ~&a, # insert the head at the first position ~&ar&& ~&arh2falrtPXPRD), # if the rest is non-empty, recursively insert at all subsequent positions ~&aNC) # no, return the singleton list of the argument