AuD
Lecture 'Algorithmen und Datenstrukturen' (code examples)
PermutationIterator.java
Go to the documentation of this file.
1package aud.util;
2
14public class PermutationIterator implements java.util.Iterator<int[]> {
15
16 private int[] p_ = null; // current permutation
17
18 void swap(int i,int j) {
19 int t=p_[i]; p_[i]=p_[j]; p_[j]=t;
20 }
21 void reverse(int i,int j) {
22 --j;
23 while (i<j)
24 swap(i++,j--);
25 }
26
30 public PermutationIterator(int n) {
31 if (n>0) {
32 p_=new int[n];
33 for (int i=0;i<n;++i)
34 p_[i]=i; // initial
35 }
36 }
37
38 @Override public boolean hasNext() {
39 return p_!=null;
40 }
41
42 @Override public int[] next() {
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 }
70
72 @Override public void remove() {
73 throw new UnsupportedOperationException();
74 }
75
77 public static void main(String[] args) {
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 }
88}
Iterator over all permutations of length n.
static void main(String[] args)
demonstration and test
PermutationIterator(int n)
create new iterator