Generating Permutations - PowerPoint PPT Presentation

About This Presentation
Title:

Generating Permutations

Description:

Title: PowerPoint Presentation Author: Peter Cappello Last modified by: Pete Cappello Created Date: 3/22/2001 5:43:43 PM Document presentation format – PowerPoint PPT presentation

Number of Views:107
Avg rating:3.0/5.0
Slides: 10
Provided by: PeterCa84
Category:

less

Transcript and Presenter's Notes

Title: Generating Permutations


1
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
  • 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)

4
10 Solution continued
  • // pseudo code of an iterator for r-permutations.
  • for ( IteratorltSetgt 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 lt r lt 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 intr
  • for ( int i 0 i lt combination.length
    i )
  • combinationi i 1
  • public boolean hasNext() return hasNext

7
  • public int next()
  • if ( isFirst )
  • isFirst false
  • if ( r 0 n lt r n 0 )
    hasNext false
  • return combination
  • int i combination.length - 1
  • // find 1st submaximal element from the
    right
  • for ( combinationi n - r i 1
    i--)
  • combinationi combinationi 1 //
    increase that element
  • // minimize subsequent elements
  • for ( int j i 1 j lt
    combination.length j )
  • combinationj combinationi j -
    i
  • // set hasNext
  • for ( i gt 0 combinationi n - r
    i 1 i--)

8
Exercise
  • Complete an Iterator class for permutations
  • class PermutationIterator
  • public PermutationIterator( int n )
  • boolean hasNext()
  • int next()
  • void remove() / null body /

9
Characters
  • ? ? ? .
  • ? ? ? ? ? ? ?
  • ? ? ?
  • ? ?? T
  • ? ? ? ? ? S
  • ? ? ? ? ? ? ? ?
Write a Comment
User Comments (0)
About PowerShow.com