s**********e 发帖数: 326 | 7 贴个我的代码:
evenProb have 50/50 probability to return true, genAnyProb can return true
with any prob(first parameter)
main should call genAnyProb like this: genAnyProb(0.6,1,0.00001)
public boolean evenProb() {
return new Random().nextInt(2) == 0;
}
public boolean genAnyProb(double prob, double base, double epsilon) {
if (prob * base < epsilon) {
return true;
}
if (prob == 0.5) {
return evenProb();
} else if (prob > 0.5) {
return evenProb() || genAnyProb((prob - 0.5) * 2, base / 2,
epsilon);
} else {
return evenProb() && genAnyProb(prob * 2, base / 2, epsilon);
}
}
sixFourProb() has 60 % probability to return true, genEvenGivenSixFour() can
return true with any probability
main should call genEvenGivenSixFour like this :
genEvenGivenSixFour(0.5, 1, 0.00001)
public boolean sixFourProb(){
Random random = new Random();
if(random.nextInt(10) <= 5){
return true;
}
else{
return false;
}
}
public boolean genEvenGivenSixFour(double prob, double base, double
epsilon){
if(prob * base < epsilon){
return true;
}
if(prob == 0.6){
return sixFourProb();
}
else if(prob < 0.6){
return sixFourProb() && genEvenGivenSixFour(prob / 0.6, base * 0
.6, epsilon);
}
else{
return sixFourProb() || genEvenGivenSixFour((prob - 0.6)/ 0.4,
base * 0.4, epsilon);
}
} |