Generating Permutations & Combinations: Selected Exercises
2
10
Develop an algorithm for generating the
r-permutations of a set of n elements.
3
10 Solution
We have algorithms to:
A) Generate the next permutation in lexicographic order
B) Generate the next r-combination in lexicographic order.
From these, we create an algorithm to generate the
r-permutations of a set with n elements:
1. Generate each r-combination, using algorithm B)
2. For each r-combination
Generate the (r!) r-permutations, using algorithm A)
4
10 Solution continued
// pseudo code of an iterator for r-permutations.
for ( Iterator<Set> ci = set.combinationIt(n,r); ci.hasNext(); )
Set s = ci.next();
for( Iterator pi = s.permutationIt(r), pi.hasNext(); )
int[] permutation = (int[]) pi.next();
5
10 continue
On the next slide, I put a crude Java
“Iterator” for generating r-combinations
based on the algorithm in the textbook.
(The previous slide does not use this.)
6
– // Assumption: 0 <= r <= n– public class CombinationIterator – – private int n; // the size of the set– private int r; // the size of the combination– private int[] combination;– private boolean hasNext = true;– private boolean isFirst = true;– – public CombinationIterator( int n, int r ) – this.n = n;– this.r = r;– combination = new int[r];– for ( int i = 0; i < combination.length; i++ )– combination[i] = i + 1;–
– public boolean hasNext() return hasNext;
7
– public int[] next() – if ( isFirst ) – isFirst = false;– if ( r == 0 || n <= r || n == 0 ) hasNext = false;– return combination;– – int i = combination.length - 1;– – // find 1st submaximal element from the right– for ( ; combination[i] == n - r + i + 1; i--);– – combination[i] = combination[i] + 1; // increase that element– – // minimize subsequent elements– for ( int j = i + 1; j < combination.length; j++ )– combination[j] = combination[i] + j - i;– – // set hasNext– for ( ; i >= 0 && combination[i] == n - r + i + 1; i--);– if ( i < 0 ) hasNext = false;– – return combination;– –
8
Exercise
Complete an “Iterator” class for permutations:class PermutationIterator
public PermutationIterator( int n )
boolean hasNext()
int[] next()
void remove() /* null body */
9
Characters
. ≥ ≡ ~
≈
Ω Θ
Σ ¢