AuD
Lecture 'Algorithmen und Datenstrukturen' (code examples)
aud.util.PermutationIterator Class Reference

Iterator over all permutations of length n. More...

+ Inheritance diagram for aud.util.PermutationIterator:
+ Collaboration diagram for aud.util.PermutationIterator:

Public Member Functions

 PermutationIterator (int n)
 create new iterator More...
 
boolean hasNext ()
 
int[] next ()
 
void remove ()
 

Static Public Member Functions

static void main (String[] args)
 demonstration and test More...
 

Detailed Description

Iterator over all permutations of length n.

Permutations are represented as int[] arrays with entries 0,..,n-1.

Implementation inspired by std::next_permutation of the C++ standard library: assume ordered sequence and "count up" to lexicographically next sequence. (Requires only sequence as state.)

Definition at line 14 of file PermutationIterator.java.

Constructor & Destructor Documentation

◆ PermutationIterator()

create new iterator

Parameters
nlength of permutation

Definition at line 30 of file PermutationIterator.java.

30 {
31 if (n>0) {
32 p_=new int[n];
33 for (int i=0;i<n;++i)
34 p_[i]=i; // initial
35 }
36 }

Member Function Documentation

◆ hasNext()

boolean aud.util.PermutationIterator.hasNext ( )

Definition at line 38 of file PermutationIterator.java.

38 {
39 return p_!=null;
40 }

Referenced by aud.util.PermutationIterator.main().

+ Here is the caller graph for this function:

◆ main()

static void aud.util.PermutationIterator.main ( String[]  args)
static

demonstration and test

Definition at line 77 of file PermutationIterator.java.

77 {
78
79 int n=args.length>0 ? Integer.parseInt(args[0]) : 3;
80
81 for (PermutationIterator ii=new PermutationIterator(n);ii.hasNext();) {
82 int[] p=ii.next();
83 for (int j : p)
84 System.out.print(j);
85 System.out.println();
86 }
87 }
PermutationIterator(int n)
create new iterator

References aud.util.PermutationIterator.hasNext().

+ Here is the call graph for this function:

◆ next()

int[] aud.util.PermutationIterator.next ( )

Definition at line 42 of file PermutationIterator.java.

42 {
43 int[] p = new int[p_.length];
44
45 for (int j=0;j<p_.length;++j)
46 p[j]=p_[j];
47
48 int last=p_.length;
49 int i=last-1;
50
51 for (;;) {
52 int ii=i;
53 if (p_[--i]<p_[ii]) {
54 int j=last;
55 while (p_[i]>=p_[--j]) {}
56 swap(i,j);
57 reverse(ii,last);
58
59 break;
60 }
61 else if (i==0) {
62 //reverse(0,last);
63 p_=null;
64 break;
65 }
66 }
67
68 return p;
69 }

◆ remove()

void aud.util.PermutationIterator.remove ( )
Exceptions
UnsupportedOperationException

Definition at line 72 of file PermutationIterator.java.

72 {
73 throw new UnsupportedOperationException();
74 }

The documentation for this class was generated from the following file: