我有一个随机数列表。由于它是随机的,我想迭代该列表并防止任何直接(跟随)重复之前的仅两个数字的组合。例如:
但我的结果显示如下:7,4,3,1,6,2,1,6,10,4,4, 7
第二个7不在正确的位置!!
我的代码看起来很好,但输出并不是我所期待的! 我不想要一个完整的非重复有序集(哈希集)!我需要它是我解释的方式!!
public static void main(String[] args) {
int[] list = {7, 4, 3, 7, 1, 6, 2, 4, 1, 6, 4, 10};
int[] lastCombination = {-1, -1}; //initial var
int[] currentCombination = new int[2]; //temp
int currentIndex = 0;
for (int i = 0; i < list.length; i++) {
if (lastCombination[0] == -1 && lastCombination[1] == -1) {
lastCombination[0] = list[i];
lastCombination[1] = list[++i];
} else {
if (list[i] != lastCombination[0] && list[i] != lastCombination[1]) { //i is not used
if (currentIndex == 1) {
currentCombination[currentIndex] = list[i];
currentIndex = 0;
} else {
currentCombination[currentIndex] = list[i];
currentIndex++;
}
} else { //i is used
boolean isNotUnique = true;
int next = i + 1;
while (isNotUnique) {
if (next <= (list.length - 1)) {
if (list[next] != lastCombination[0] && list[next] != lastCombination[1]) {
int temp = list[i];
list[i] = list[next];
list[next] = temp;
i = i - 1;
isNotUnique = false;
} else {
next++;
}
} else {
System.out.println("REACHED THE END");
isNotUnique = false;
}
}
}
}
}
System.out.println("");
System.out.println("Original: 7, 4, 3, 7, 1, 6, 2, 4, 1, 6, 4, 10");
System.out.print("Modified; ");
for (int i : list) {
System.out.print(i + ", ");
}
}
&#13;