| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.util; |
| 27 |
|
| 28 |
import java.lang.reflect.Array; |
| 29 |
import java.util.Iterator; |
| 30 |
import java.util.NoSuchElementException; |
| 31 |
|
| 32 |
public class Permutator implements Iterator { |
| 33 |
|
| 34 |
private final int size; |
| 35 |
private final Object [] elements; |
| 36 |
private final Object ar; |
| 37 |
private final int [] permutation; |
| 38 |
|
| 39 |
private boolean next = true; |
| 40 |
|
| 41 |
|
| 42 |
public Permutator (Object [] e) { |
| 43 |
size = e.length; |
| 44 |
elements = new Object [size]; |
| 45 |
System.arraycopy (e, 0, elements, 0, size); |
| 46 |
ar = Array.newInstance (e.getClass().getComponentType(), size); |
| 47 |
System.arraycopy (e, 0, ar, 0, size); |
| 48 |
permutation = new int [size+1]; |
| 49 |
for (int i=0; i<size+1; i++) { |
| 50 |
permutation [i]=i; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
private void formNextPermutation () { |
| 55 |
for (int i=0; i<size; i++) { |
| 56 |
|
| 57 |
|
| 58 |
Array.set (ar, i, elements[permutation[i+1]-1]); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
public boolean hasNext() { |
| 63 |
return next; |
| 64 |
} |
| 65 |
|
| 66 |
public void remove() throws UnsupportedOperationException { |
| 67 |
throw new UnsupportedOperationException(); |
| 68 |
} |
| 69 |
|
| 70 |
private void swap (final int i, final int j) { |
| 71 |
final int x = permutation[i]; |
| 72 |
permutation[i] = permutation [j]; |
| 73 |
permutation[j] = x; |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
public Object next() throws NoSuchElementException { |
| 78 |
|
| 79 |
formNextPermutation (); |
| 80 |
|
| 81 |
int i = size-1; |
| 82 |
while (permutation[i]>permutation[i+1]) i--; |
| 83 |
|
| 84 |
if (i==0) { |
| 85 |
next = false; |
| 86 |
for (int j=0; j<size+1; j++) { |
| 87 |
permutation [j]=j; |
| 88 |
} |
| 89 |
return ar; |
| 90 |
} |
| 91 |
|
| 92 |
int j = size; |
| 93 |
|
| 94 |
while (permutation[i]>permutation[j]) j--; |
| 95 |
swap (i,j); |
| 96 |
int r = size; |
| 97 |
int s = i+1; |
| 98 |
while (r>s) { swap(r,s); r--; s++; } |
| 99 |
|
| 100 |
return ar; |
| 101 |
} |
| 102 |
|
| 103 |
public String toString () { |
| 104 |
final int n = Array.getLength(ar); |
| 105 |
final StringBuffer sb = new StringBuffer ("["); |
| 106 |
for (int j=0; j<n; j++) { |
| 107 |
sb.append (Array.get(ar,j).toString()); |
| 108 |
if (j<n-1) sb.append (","); |
| 109 |
} |
| 110 |
sb.append("]"); |
| 111 |
return new String (sb); |
| 112 |
} |
| 113 |
|
| 114 |
public static void main (String [] args) { |
| 115 |
for (Iterator i = new Permutator(args); i.hasNext(); ) { |
| 116 |
i.next(); |
| 117 |
System.out.println (i); |
| 118 |
} |
| 119 |
} |
| 120 |
} |