Previous Up Next

6.9.2  Previous and next permutation: prevperm nextperm

The set of n-tuples of an ordered set can be put in lexicographic order, where the tuple (a1,a2,…,an) comes before (b1,b2,…,bn) exactly when for some k (possibly k=0), ai=bi for i=1,…,k−1 and ak<bk. For example, the set of permutations of size 3 in lexicographic order is

(0,1,2)
(0,2,1)
(1,0,2)
(1,2,0)
(2,0,1)
(2,1,0)

The prevperm and nextperm commands find the preceding and succeeding permutation.


Example.
Input:

prevperm([0,3,1,2])

Output:


0,2,3,1



Example.
Input:

nextperm([0,2,3,1])

Output:


0,3,1,2

Previous Up Next