CMPSCI 250 Discussion #10: Generating Permutations and Combinations

David Mix Barrington

5 December 2007

The exercise was to write several additional methods for the following Java class. Throughout, a "sequence" is a sequence of k elements of the set {1,...,n}, a "permutation" is a sequence that does not have two or more equal elements, and a "set" is a permutation whose elements occur in order. Here is the code I provided, with one addition -- a copy constructor that has the same effect as a "clone" method:


     public class Sequence
     {// Stores sequence of k elements from set of naturals from 1 to n
         static int k,n; // class variables, fixed for the problem
         int [] values = new int[k];

     public Sequence()
     {// Constructs first sequence in order, all ones
         for (int i=0; i < k; i++)
             values[i] = 1;}

     public Sequence(Sequence s)
     {// Copy Constructor
         this();
         for (int i=0; i < k; i++)
             values[i] = s.values[i];}

     public static Sequence firstSet();
     {// Returns sequence [1,...,k]
         Sequence s = new Sequence();
         for (int i=0; i < k; i++)
             s.values[i] = i+1;
         return s;}

     public String toString ()
     {// Returns String describing calling sequence
         String w = "";
         if (k > 0) w += values[0];
         for (int i=1; i < k; i++)
             w += " " + values[i];
         return w;}

     public void listSequences
     {// Prints all sequences in order
         Sequence s = new Sequence();
         while (!isLast()) {
             System.out.println (s);
             s = s.next();}
         System.out.println(s);}

     public void listSets()
         Sequence s = firstSet();
         while (!isLastSet()) {
             System.out.println(s);
             s = s.nextSet();}
         System.out.println(s);}

     public boolean isPerm()
     {// returns whether this Sequence is a permutation
          for (int i=0; i < k; i++)
              for (int j = i+1; j < k; j++)
                  if (values[i] == values[j]) return false;
          return true;}

Writing Exercises (solutions in blue)

Last modified 6 December 2007