假设你有一个要求,即所有可能的结果是等可能的,那么唯一的简单的方法将是穷举创建所有组合,然后从该随机选择。所有组合都是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;
}
你试过了什么? – Alex
你的方法是错误的 - 它可能需要很多重试才能通过随机混洗列表来达到所需的状态。你应该想出一个算法,强制所需的洗牌,例如,通过混洗奇数和偶数分开,然后合并它们。 – dasblinkenlight
@Alex:我尝试只是说明几个if语句等: 如果(rng.get(ⅰ).equals(0)&& rng.get第(i + 1).equals(1)){Collections.shuffle(RNG) ;} – Joilin