我正在寻找一个随机数生成器,它偏向于给出距一组已选择的数字“最远”的数字。例如,如果我的范围是 [1, 50] 并且我传入一组数字,例如 (1, 20, 40),那么我希望生成器“更喜欢”生成远离 1、20 和40. 因此,50或30这样的数字比20或40更有可能被抽中。我怀疑这种情况可能已经存在。有谁知道我可以在 Java 中使用这样的实现吗?
最佳答案
这是一种可以手动完成的方法。基本上,我们的想法是,我们接受一些我们不想生成的数字,然后生成一个随机数,如果该数字位于我们不希望生成的数字列表中,我们将再次尝试,直到达到最大重试次数。
public static void main(String[] args) {
int times = 25;
int[] listOfNumbers = {1, 2, 3};
int max = 5, min = 1;
while(times-- > 0)
{
System.out.print(GeneratePreferredNumbers(listOfNumbers, max, min) + " ");
}
}//main method
public static Integer GeneratePreferredNumbers(int[] listOfNotPreffered, int max, int min)
{
Random rand = new Random();
int randomNum;
int retry = 1; //increasing this lessons the likely of our non-preferred numbers to show up
HashSet<Integer> notPrefer = new HashSet<>();
//add all the numbers we don't want to generate into a HashSet for easy lookup
for(int index = 0; index < listOfNotPreffered.length; index++)
notPrefer.add(listOfNotPreffered[index]);
do {
randomNum = rand.nextInt((max - min) + 1) + min;
if(notPrefer.contains(randomNum))
{
retry--;
}
//we found a good value, let's return it
else{
retry = 0;
}
} while (retry > 0);
return randomNum;
}
输出:
重试= 0(只是随机)
2 2 4 4 4 2 1 2 2 4 3 3 4 5 4 4 1 5 3 2 1 2 3 3 1
重试 = 1
1 2 5 3 3 4 3 1 2 1 4 1 3 3 1 1 5 3 5 4 2 1 3 4 5
重试 = 2
3 3 2 4 4 2 2 1 4 5 5 5 4 2 1 4 5 1 4 5 1 4 4 2 2
重试 = 3
5 5 5 5 4 4 4 4 2 4 5 5 1 4 5 4 3 5 4 4 4 5 3 1 2
重试 = 4
5 4 5 4 4 4 5 5 4 4 5 1 5 2 5 5 5 2 4 5 5 2 4 4 4
重试 = 5
4 4 4 4 4 4 4 4 5 5 4 4 5 4 5 4 4 5 4 5 4 5 5 5 5
注意:我们允许算法重试的次数越多,我们的输出就越有可能包含我们想要的数字。这使您可以控制希望这些非首选号码显示的可能性。这是有道理的,因为如果我们将重试次数增加到无限,只有当生成的数字不包含在我们的非首选数字列表中时,才会停止。
希望这有帮助!
关于java - 有偏随机数生成器 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41580650/