Java: random integer with non-uniform distribution

前端 未结 11 1593
终归单人心
终归单人心 2020-12-13 12:55

How can I create a random integer n in Java, between 1 and k with a "linear descending distribution", i.e. 1 is

11条回答
  •  [愿得一人]
    2020-12-13 13:12

    The simplest thing to do it to generate a list or array of all the possible values in their weights.

    int k = /* possible values */
    int[] results = new int[k*(k+1)/2];
    for(int i=1,r=0;i<=k;i++)
       for(int j=0;j<=k-i;j++)
           results[r++] = i;
    // k=4 => { 1,1,1,1,2,2,2,3,3,4 }
    
    // to get a value with a given distribution.
    int n = results[random.nextInt(results.length)];
    

    This best works for relatively small k values.ie. k < 1000. ;)

    For larger numbers you can use a bucket approach

    int k = 
    int[] buckets = new int[k+1];
    for(int i=1;i

    The cost of the binary search is fairly small but not as efficient as a direct look up (for a small array)


    For an arbitary distrubution you can use a double[] for the cumlative distrubution and use a binary search to find the value.

提交回复
热议问题