gpt4 book ai didi

Java - 生成随机数字簇

转载 作者:行者123 更新时间:2023-11-29 05:03:44 24 4
gpt4 key购买 nike

我有一个数组,我想从该数组中“随机”选择一些东西,但我希望它获得簇的概率更高。

例如:

arr = [1, 3, 4, 6, 7, 9, 10]
x = Math.random() * arr.length;
return arr[x]

如果 x 结果为 3,则该函数将返回 6。如何增加下一个数字 x 为 2 或 4 的可能性(然后是 1 和 5 等等,概率曲线越远离当前 x)。这可行吗?

最佳答案

使用归一化高斯分布我会做这样的事情:

public class ClusterRandom{

Random dice = new Random();
int mRange;
int mWidth = 1;
int mMean;

public ClusterRandom(int range, int startingMean, int...width){
mRange = range;
mMean = startingMean;
if(width.length > 0)
mWidth = width[0];
}

public int nextInt(){

int pick;

do{
pick = (int) Math.round((dice.nextGaussian()*mWidth) + mMean);
}while(pick < 0 || pick >= mRange);

mMean = pick;
return pick;

}

}

然后在你的代码中:

int[] arr = new int[]{1, 3, 4, 6, 7, 9, 10};
// for example starting from index 3 which is 6
ClusterRandom clusterDice = new ClusterRandom(arr.length, 3);
// ...
// in loop
return arr[clusterDice.nextInt()];

关于Java - 生成随机数字簇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31138925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com