90 likes | 112 Views
Generating Permutations & Combinations: Selected Exercises. 10. Develop an algorithm for generating the r - permutations of a set of n elements. 10 Solution. We have algorithms to: Generate the next permutation in lexicographic order
E N D
10 Develop an algorithm for generating the r-permutations of a set of n elements.
10 Solution We have algorithms to: • Generate the next permutation in lexicographic order • 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: • Generate each r-combination, using algorithm B) • For each r-combination Generate the (r!)r-permutations, using algorithm A)
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(); } }
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.)
// 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; }
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; • } • }
Exercise Complete an “Iterator” class for permutations: class PermutationIterator { public PermutationIterator( int n ) boolean hasNext() int[] next() void remove() { /* null body */ } }
Characters • .≥ ≡ ~ ┌ ┐└┘ • ≈ • • Ω Θ • Σ ¢ •