Hallo Comm.,
ich versuche gerade, den Johnson and Trotter algorithm in Java umzusetzen (alle Permutationen (iterativ) berechnen), aber scheitere kläglich… Könnt ihr mir sagen, was daran falsch ist - oder wenigstens, was daran richtig wäre?
public static void JohnsonAndTrotterAlgorithm(int[] a) {
boolean[] direction = new boolean[a.length];
boolean[] mobile = new boolean[a.length];
for (int j = 0; j < 20; j++) {
int max = getLargestMobileIndex(a, mobile);
if (!direction[max]) {
if (max - 1 < 0) {
mobile[max] = !mobile[max];
} else if (a[max] > a[max - 1]) {
int t = a[max];
a[max] = a[max - 1];
a[max - 1] = t;
System.out.println(Arrays.toString(a));
} else {
direction[max] = !direction[max];
}
} else {
if (max + 1 == a.length) {
mobile[max] = !mobile[max];
} else if (a[max] > a[max + 1]) {
int t = a[max];
a[max] = a[max + 1];
a[max + 1] = t;
System.out.println(Arrays.toString(a));
} else {
direction[max] = !direction[max];
}
}
}
}
public static int getLargestMobileIndex(int[] a, boolean[] mobile) {
int maxIndex = 0;
for (int i = 0; i < a.length; i++) {
if (!mobile[i]) {
maxIndex = i;
break;
}
}
for (int i = 0; i < a.length; i++) {
if (!mobile[i] && a[i] > a[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
public static void main(String[] args) {
JohnsonAndTrotterAlgorithm(new int[] { 1, 2, 3, 4, 5 });
}
Ich weiß nicht genau,
- wann ein Index nicht mehr mobil ist,
- wann ein Richtungswechsel erfolgt,
- welcher Index in einer Iteration vertauscht wird,
- wie lange das Ganze/(j) läuft,
- etc.
Schonmal vielen Dank & schönen Abend