Please answer the questions during the discussion period.
The permutations of an n-element set are the n! different
listings of it as a sequence. Here is a Java class that stores a
permutation as an array of int
variables with the numbers
{1,...,n} in some order. The second array arrow
is used
in the Johnson-Trotter algorithm below.
public class Permutation
int n; // size of set
int [] a; // values from 1 through n in some order
boolean [] arrow; // true means left, false means right
public Permutation (size)
{// creates new identity permutation of given size
n = size;
a = new int[n];
arrow = new boolean[n];
for (int i=0; i < n; i++)
{a[i] = i+1; arrow[i] = true;}
public void swap (int i, int j)
{// swaps both value and arrow in position i and j
int ti = a[i]; a[i] = a[j]; a[j] = ti;
boolean tb = arrow[i]; arrow[i] = arrow[j]; arrow[j] = tb;}
boolean
method next()
that changes the calling Permutation
into the next one given by the Johnson-Trotter method, updating the arrows.
Levitin's description of the process is ``if there is a mobile integer k,
find the largest one, swap it with the neighbor it points to, and reverse the
arrows of all integers larger than k''. ``Mobile'' means ``pointing to a
smaller integer''. Your method should return true
if the update
happens, or false
if there is no mobile integer.
This method would be used as follows to print all the permutations of size n:
Permutation p = new Permutation(n);
boolean done = false;
while (!done) {
System.out.println(p); // using a "toString" method to be written
done = !p.next();}
boolean
method lex
that changes the
calling Permutation
to the next one in lexicographical order. Ignore the arrows. Levitin gives
an outline for this: ``If the last item an-1 is
greater than the next
to last item an-2, swap them.
Otherwise find the largest i such that
ai < ai+1. Let aj be the smallest
value with j > i and aj > ai.
Put aj in position i, and fill positions ai+1 through
an-1
with the rest of the elements formerly in positions ai through
an-1,
in increasing order.'' (I found the easiest way to do this was to make a new
array b element by element, without changing a, and then assign b
to a.)
Again, your method should return true
if the change is made and
false
if the current
Permutation is already last in lexicographic order.
Last modified 22 October 2003