Is there an efficient way to generate N random integers in a range that have a given sum or average?

前端 未结 5 1220
感动是毒
感动是毒 2020-11-27 19:15

Is there an efficient way to generate a random combination of N integers such that—

  • each integer is in the interval [min, max],
5条回答
  •  半阙折子戏
    2020-11-27 19:26

    If you generate 0≤a≤1 of the random values in the range [l, x-1] uniformly, and 1-a of the random values in the range [x, h] uniformly, the expected mean would be:

    m = ((l+x-1)/2)*a + ((x+h)/2)*(1-a)
    

    So if you want a specific m, you can play with a and x.

    For example, if you set x = m: a = (h-m)/(h-l+1).

    To ensure closer-to-uniform probability for different combinations, choose a or x randomly from the set of valid solutions to the equation above. (x must be in the range [l, h] and should be (close to) an integer; N*a should be (close to) an integer as well.

提交回复
热议问题