Generating Permutations Combinations Selected Exercises 10 Develop an

Generating Permutations & Combinations: Selected Exercises

10 Develop an algorithm for generating the r -permutations of a set of n elements. 2

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 rpermutations 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) 3

10 Solution continued // pseudo code of an iterator for r-permutations. for ( Iterator<Set> ci = set. combination. It(n, r); ci. has. Next(); ) { Set s = ci. next(); for( Iterator pi = s. permutation. It(r), pi. has. Next(); ) { int[] permutation = (int[]) pi. next(); } } 4

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. ) 5

– // Assumption: 0 <= r <= n – public class Combination. Iterator – { – private int n; // the size of the set – private int r; // the size of the combination – private int[] combination; – private boolean has. Next = true; – private boolean is. First = true; – – public Combination. Iterator( 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 has. Next() { return has. Next; } 6
![– public int[] next() { – if ( is. First ) { – is. – public int[] next() { – if ( is. First ) { – is.](http://slidetodoc.com/presentation_image_h/1238c7600359182c9d3a405acbd6e870/image-7.jpg)
– public int[] next() { – if ( is. First ) { – is. First = false; – if ( r == 0 || n <= r || n == 0 ) has. Next = false; – return combination; – } – int i = combination. length - 1; – – // find 1 st 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 has. Next – for ( ; i >= 0 && combination[i] == n - r + i + 1; i--); – if ( i < 0 ) has. Next = false; – – return combination; – } 7

Exercise Complete an “Iterator” class for permutations: class Permutation. Iterator { public Permutation. Iterator( int n ) boolean has. Next() int[] next() void remove() { /* null body */ } } 8

- Slides: 9