假设您要求所有可能的结果都同样可能,那么唯一简单的方法就是暴力创建所有组合,然后从中随机选择。所有的组合都是7! == 7*6*5*4*3*2*1 == 5040
真正不多的组合。不过,对于更大的数字,我不推荐这种方法。
List<int[]> valid = new ArrayList<>(5040);
recursiveBuild(valid, new int[] {}, new int[] { 0,1,2,3,4,5,6));
recursiveBuild 在哪里:
void recursiveBuild(List<int[]> valid, int[] soFar, int[] remaining) {
if (remaining.length == 0) {
// Check the whole thing is valid - can maybe skip this check
// if the character-by-character check covers everything
if (isValid(soFar)) {
valid.add(soFar);
}
} else {
for (int i=0;i<remaining.length;i++) {
int[] newSoFar = new int[soFar.length+1];
for (int j=0;j<soFar.length;j++) {
newSoFar[j]=soFar[j];
}
newSoFar[newSoFar.length-1]=remaining[i];
int[] newRemaining = new int[remaining.length-1];
for (int j=0;j<newRemaining.length;j++) {
if (j>=i) {
newRemaining = remaining[j+1];
} else {
newRemaining = remaining[j];
}
}
// Only continue if the new character added is valid
if (isValid(newSoFar, newSoFar.length-1)
recursiveBuild(valid, newSoFar, newReamining);
}
}
}
为了解决您列出的实际问题,我将使用策略模式的变体,将每个规则定义为其自己的对象(在 Java 8 中,闭包将使这变得不那么冗长):
interface CheckCondition {
boolean passesCondition(int index, int[] arr);
}
CheckCondition[] conditions = new CheckCondition[] {
new CheckCondition() {
@override
public boolean passesCondition(int index, int[] arr) {
// The list has to start with an even number
return index!=0 || arr[index]%2==0;
}
},
new CheckCondition() {
@override
public boolean passesCondition(int index, int[] arr) {
// an even number can't follow an even number, unless it's 6.
return index==0 || arr[index]==6 || arr[index]%2==1 || arr[index-1]%2==1;
}
},
new CheckCondition() {
@override
public boolean passesCondition(int index, int[] arr) {
// a number can't be followed by the next closest one unless its 6
return index==0 || arr[index]!=arr[index-1]-1 || arr[index]==6;
}
},
};
现在使用这些规则来检查有效性:
boolean isValid(int[] arr, int index) {
for (CheckCondition c: conditions)
if (!c.passesCondition(arr.length-1, arr)
return false;
return true;
}
boolean isValid(int[] arr) {
for (int i=0;i<arr.length;i++) {
if (!isValid(arr, i);
return false;
}
return true;
}