Java - 生成随机数字簇

时间:2015-06-30 12:56:36

标签: java random probability

我有一系列的东西,我想“随机”从该数组中选择东西,但我希望它有可能让集群更高。

例如:

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得到的距离越远。这可行吗?

2 个答案:

答案 0 :(得分:2)

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

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()];

答案 1 :(得分:1)

Question is kind of generic, so will be my answer.

Understanding of what you want to achieve is easiest(for me) with geometrical probability.

Let's start with your first case, so index is random, and let's assume you have array of length 5.

   0  |_|_|_|_|_| 5

Then you choose a random value from set of <0,1,2,3,4>. At this level of accuracy we might assume they are equally probable.

So what if we want to make just one of them twice as probable as the others? We widen the slot for that index.

   0  |_ _|_|_|_|_| 5

Now we choose a value from set of <0,1,2,3,4,5> but, we say that both 0 and 1 mean choice of element at index 0.

So if we kept the second array, in which we would keep width of its slot, we could still randomize the result, but it would match it against the range of values(of custom length) thus making one more/less probable than the other.

My approach would be then to create that second array of integers, write function taking this array and the first random index, fill them with upper bound of the range (lower would be at index--). That range would be related to distance from the first index, making the first random index central.

Then you create one more function that makes randomization, matches result with array of ranges and returns corresponding element from elements array.

That might be naive, but that's one I would understand. Hope it helps.